子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。
#include <pthread.h>#include <stdio.h>#include <unistd.h>
static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static void *thread_func(void *arg){ //sleep(10); int j=3; while(j--) {
pthread_mutex_lock(&mtx); pthread_cond_wait(&cond,&mtx); //pthread printf("10 times complete.\n"); //pthread pthread_mutex_unlock(&mtx); }}
int main(void *arg){ pthread_t tid; pthread_create(&tid,NULL,thread_func,NULL); //sleep(5); int i=50; while(i--) { sleep(2); pthread_mutex_lock(&mtx); printf("100 times complete!.\n"); pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx); } //pthread_join(tid,NULL); //pthread_cancel(tid); pthread_join(tid,NULL);}
