题目:
子线程循环 3 次,接着主线程循环 6 次,接着又回到子线程循环 3 次,接着再回到主线程又循环6 次,如此循环50次,试写出代码。
程序:
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- int main_flog = 0;
- int sub_flog = 0;
- int main_count = 0;
- int sub_count = 0;
- void *sub_thread_func(void *argv);
- void main_thread_func();
- int main()
- {
- pthread_t tid;
- int ret;
- pthread_mutex_init(&mutex,NULL);
- pthread_cond_init(&cond,NULL);
- ret = pthread_create(&tid,NULL,sub_thread_func,NULL);
- if(ret == -1)
- {
- perror("pthread_create errpr!\n");
- exit(-1);
- }
- main_thread_func();
- ret = pthread_join(tid,NULL);
- if(ret == -1)
- {
- printf("pthread_join error!\n");
- exit(-1);
- }
- return 0;
- }
- void *sub_thread_func(void *argv)
- {
- int i;
- while(1)
- {
- sub_count++;
- for(i = 1; i <= 3; i++)
- {
- printf("sub pthread%d:%d\n",sub_count,i);
- }
- while(1)
- {
- pthread_mutex_lock(&mutex);
- if(main_flog == 1)
- {
- pthread_cond_signal(&cond);
- pthread_mutex_unlock(&mutex);
- break;
- }
- pthread_mutex_unlock(&mutex);
- }
- pthread_mutex_lock(&mutex);
- sub_flog = 1;
- pthread_cond_wait(&cond,&mutex);
- sub_flog = 0;
- pthread_mutex_unlock(&mutex);
- //sub_count++;
- if(sub_count >= 50)
- {
- printf("sub_pthread loop 50 times!\n");
- break;
- }
- }
- return (void *)0;
- }
- void main_thread_func(void)
- {
- int i;
- while(1)
- {
- main_count++;
- pthread_mutex_lock(&mutex);
- main_flog = 1;
- pthread_cond_wait(&cond,&mutex);
- main_flog = 0;
- pthread_mutex_unlock(&mutex);
- for(i = 1; i <= 6; i++)
- {
- printf("main phread%d:%d\n",main_count,i);
- }
- while(1)
- {
- pthread_mutex_lock(&mutex);
- if(sub_flog == 1)
- {
- pthread_cond_signal(&cond);
- pthread_mutex_unlock(&mutex);
- break;
- }
- pthread_mutex_unlock(&mutex);
- }
- //main_count++;
- if(main_count >= 50)
- {
- printf("main_phread loop 50 times!\n");
- break;
- }
- }
- }