子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> pthread_attr_t attr; pthread_mutex_t mutex; pthread_cond_t cond; pthread_t pid; int flag1 = 0, flag2 = 0; void *func(void *arg) { int i, k = 0; while( 1) { for(i = 1; i <= 10; i++ ) printf("%d ", i); printf("\n"); pthread_mutex_lock(&mutex); flag2 = 1; pthread_cond_signal(&cond); while(flag1 != 1) { pthread_cond_wait(&cond, &mutex); } flag1 = 0; pthread_mutex_unlock(&mutex); k++; if(k ==4) pthread_exit(NULL); } } int main() { int i, k = 0; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_attr_init( &attr); /*属性*/ pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED); pthread_create(&pid, &attr, func, NULL ); while(1) { pthread_mutex_lock(&mutex); while(flag2 != 1) { pthread_cond_wait(&cond, &mutex); } flag2 = 0; for(i = 0; i < 100; i++) { printf("%d ",i+1); } printf("\n"); flag1 = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); k++; if(k == 4) { /*pthread_cancel(pid); sleep(1);*/ exit(0); } } exit(0); }
问题在于pthread_cond_signal时,接收线程必须准备好。这让3个线程搅在一起,果断弄晕了。
算了,还是用匿名信号灯,不过我想考这题的初衷是考互斥锁加条件吧。
(迅雷笔试题):
编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> //#include "unpipc.h" #include <semaphore.h> pthread_t pidA, pidB, pidC; pthread_attr_t attr; sem_t semA, semB, semC; void *funcA(void *arg); void *funcB(void *arg); void *funcC(void *arg); int main( ) { int i; //pthread_attr_init( &attr); /*属性*/ //pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED); sem_init(&semA, 0, 1); sem_init(&semB, 0, 0); sem_init(&semC, 0, 0); pthread_create(&pidA, &attr, funcA, (void *)&pidA ); pthread_create(&pidB, &attr, funcB, (void *)&pidB ); pthread_create(&pidC, &attr, funcC, (void *)&pidC ); pthread_join(pidA, NULL); pthread_join(pidB, NULL); pthread_join(pidC, NULL); sem_destroy(&semA); sem_destroy(&semB); sem_destroy(&semC); exit(0); } void *funcA(void *arg) { long pid = *(long *)arg; int i; for(i = 0; i< 10; i++){ sem_wait(&semA); printf("A"); /*printf("%ld ", pid);*/ fflush(stdout); sem_post(&semB); } return NULL; } void *funcB(void *arg) { long pid = *(long *)arg; int i; for(i = 0; i< 10; i++){ sem_wait(&semB); printf("B", i);/*printf("%ld ", pid);*/ fflush(stdout); sem_post(&semC); } return NULL; } void *funcC(void *arg) { long pid = *(long *)arg; int i; for(i = 0; i< 10; i++){ sem_wait(&semC); printf("C");/*printf("%ld ", pid);*/ fflush(stdout); sem_post(&semA); } return NULL; }
时间: 2024-10-29 19:13:30