问题描述
用gcc编译。我跑这来看看为什么我用我的其他程序都信号灯无法正常工作。我只是用这些不当或什么?该字符串输出每次即使信号灯应停止执行,并导致死锁,对不对?
Compiled with gcc. I ran this to see why the semaphores I was using in my other programs were not working correctly. Am I just using these them incorrectly or what? The string is outputted every time even though the semaphore should halt execution and cause a deadlock, right?
下面是code:
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#define NUM_THREADS 5
void printHello();
int main(){
int i;
pthread_t threads[NUM_THREADS];
sem_t sem1;
sem_init(&sem1, 0, 0);
sem_wait(&sem1);
for(i = 0; i < NUM_THREADS; i++){
pthread_create(&threads[i], NULL, &printHello, NULL);
}
sem_destroy(&sem1);
pthread_exit(NULL);
return 0;
}
void printHello(){
printf("sem_wait failed\n");
}
任何帮助将大大AP preciated因为我试图把握整个概念的多线程
Any help would be greatly appreciated as I am trying to grasp the whole multithreading concept.
谢谢!
推荐答案
这code看起来不错。那么,它会更改启动功能后无效* printHello(无效*)
和在pthread_join
让你不ŧ破坏信号灯和退出。但信号块,正是因为它应该在Linux上。
That code looks fine. Well, it will after you change the start function to void *printHello(void *)
and pthread_join
so you don't destroy the semaphore and exit. But the semaphore blocks exactly as it should on linux.
您在运行OSX?显然OSX不支持POSIX无名信号量。如果是这样的话,你需要使用一个名为POSIX信号即 sem_open
,而不是 sem_init
。
Are you running on OSX? Apparently OSX does not support unnamed POSIX semaphores. If that is the case you need to use named POSIX semaphores i.e. sem_open
rather than sem_init
.
这篇关于sem_wait没有基本的code工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!