How to synchronize manager/worker pthreads without a join?

后端 未结 4 1640
后悔当初
后悔当初 2021-02-01 10:28

I\'m familiar with multithreading and I\'ve developed many multithreaded programs in Java and Objective-C successfully. But I couldn\'t achieve the following in C using pthreads

4条回答
  •  借酒劲吻你
    2021-02-01 10:50

    To tell all the threads to start working, it can be as simple as a global integer variable which is initialized to zero, and the threads simply wait until it's non-zero. This way you don't need the while (1) loop in the thread function.

    For waiting until they are all done, pthread_join is simplest as it will actually block until the thread it's joining is done. It's also needed to clean up system stuff after the thread (like otherwise the return value from the thread will be stored for the remainder of the program). As you have an array of all pthread_t for the threads, just loop over them one by one. As that part of your program doesn't do anything else, and has to wait until all threads are done, just waiting for them in order is okay.

提交回复
热议问题