【发布时间】:2019-06-15 12:40:42
【问题描述】:
我正在尝试编写一个使用信号量打印
我也试过pthread_join,但还是一样:无论如何都不会打印。
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
sem_t f1, f2, f3;
int done = 1;
void *threadfunc(void *n) {
int a = 0;
while (1) {
if ((int)*(int *)n == 1) {
//printf("1st THREAD!\n");
printf("<ONE>");
sem_wait(&f1);
} else if ((int)*(int *)n == 2) {
//printf("2st THREAD!\n");
printf("<TWO>");
sem_wait(&f2);
} else {
//printf("3st THREAD!\n");
printf("<THREE>");
sem_wait(&f3);
}
//}
if (done == 3) {
done = 1;
sem_post(&f1);
} else if (done == 1) {
done = 2;
sem_post(&f2);
} else if (done == 2) {
done = 3;
sem_post(&f3);
}
}
}
int main() {
pthread_t tid1, tid2, tid3;
int n1 = 1, n2 = 2, n3 = 3;
for (;;) {
// Create 3 threads
pthread_create(&tid1, NULL, threadfunc, (void *)&n1);
sleep(1);
pthread_create(&tid2, NULL, threadfunc, (void *)&n2);
sleep(1);
pthread_create(&tid3, NULL, threadfunc, (void *)&n3);
sleep(1);
// infinite loop to avoid exit of a program/process
}
return 0;
}
预期输出:ONE TWO THREE ONE TWO THREE等。
实际输出:无
【问题讨论】:
-
您不断创建线程而不是仅仅创建 3 个线程,所以也许考虑删除 'for(;;)' 并在 main 中为每个线程使用
pthread_join(tidx, NULL); -
您可能希望在创建线程之前使用
sem_init初始化您的信号量。 -
你能告诉我如何初始化信号量吗,因为我是新手,我不知道该怎么做,提前谢谢。
-
"我是新手" 阅读相关文档怎么样,例如
man sem_init?
标签: c multithreading semaphore