子線程循環 10 次,接著主線程循環 100 次,接著又回到子線程循環 10 次,接著再回到主線程又循環 100 次,如此循環50次,試寫出代碼。
要注意條件變量的自動復位問題。參看這篇文章:Linux 的多線程編程的高效開發經驗 http://www.linuxidc.com/Linux/2009-04/19615.htm
代碼:
- #include <pthread.h>
- #include <stdio.h>
-
- // 互斥鎖,條件變量
- pthread_mutex_t mutex;
- pthread_cond_t cond;
-
- // 循環次數
- int main_count = 0;
- int subthread_count = 0;
-
- // 線程等待標志
- bool main_thread_wait_flag = false;
- bool subthread_wait_flag = false;
-
- void main_thread_func();
- void *subthread_func(void *arg);
-
- int main(int argc, char **argv)
- {
- pthread_t tid;
-
- pthread_mutex_init(&mutex, NULL);
- pthread_cond_init(&cond, NULL);
-
- pthread_create(&tid, NULL, subthread_func, NULL);
- main_thread_func();
- pthread_join(tid, NULL);
-
- return 0;
- }
-
- void main_thread_func()
- {
- while (true)
- {
- pthread_mutex_lock(&mutex);
- main_thread_wait_flag = true;
- pthread_cond_wait(&cond, &mutex);
- main_thread_wait_flag = false;
- pthread_mutex_unlock(&mutex);
-
- for (int i = 1; i <= 100; ++i)
- {
- fprintf(stdout, "main thread: %d\n", i);
- }
-
-
- while (true)
- {
- pthread_mutex_lock(&mutex);
- if (true == subthread_wait_flag)
- {
- pthread_cond_signal(&cond);
- pthread_mutex_unlock(&mutex);
- break;
- }
- pthread_mutex_unlock(&mutex);
- }
-
- ++main_count;
- if (main_count >= 50)
- {
- fprintf(stdout, "main thread loop 50 times\n");
- break;
- }
- }
- }
-
- void *subthread_func(void *arg)
- {
- while (true)
- {
- for (int i = 1; i <= 10; ++i)
- {
- fprintf(stdout, "subthread: %d\n", i);
- }
-
- while (true)
- {
- pthread_mutex_lock(&mutex);
- if (true == main_thread_wait_flag)
- {
- pthread_cond_signal(&cond);
- pthread_mutex_unlock(&mutex);
- break;
- }
- pthread_mutex_unlock(&mutex);
- }
- pthread_mutex_lock(&mutex);
- subthread_wait_flag = true;
- pthread_cond_wait(&cond, &mutex);
- subthread_wait_flag = false;
- pthread_mutex_unlock(&mutex);
-
- ++subthread_count;
- if (subthread_count >= 50)
- {
- fprintf(stdout, "subthread loop 50 times\n");
- break;
- }
- }
- return (void *)0;
- }