【发布时间】:2014-10-19 15:55:06
【问题描述】:
我正在尝试创建许多不同的线程,这些线程需要等待所有线程被创建,然后才能执行任何操作。这是一个大型程序的一小部分,我只是想逐步进行。在创建每个线程时,它会立即被信号量阻塞。创建完所有线程后,我循环并释放所有线程。然后我希望每个线程都打印出它的线程号来验证它们是否都在等待。我只允许一个线程使用另一个信号量一次打印。
我遇到的问题是,虽然我创建了 #1-10 线程,但一个线程打印出它是 #11。此外,一些线程说它们与另一个线程具有相同的编号。是我传递 threadID 的错误还是我的同步中的错误?
这里是相关代码:
//Initialize semaphore to 0. Then each time a thread is spawned it will call
//semWait() making the value negative and blocking that thread. Once all of the
//threads are created, semSignal() will be called to release each of the threads
sem_init(&threadCreation,0,0);
sem_init(&tester,0,1);
//Spawn all of the opener threads, 1 for each valve
pthread_t threads[T_Valve_Numbers];
int check;
//Loop starts at 1 instead of the standard 0 so that numbering of valves
//is somewhat more logical.
for(int i =1; i <= T_Valve_Numbers;i++)
{
cout<<"Creating thread: "<<i<<endl;
check=pthread_create(&threads[i], NULL, Valve_Handler,(void*)&i);
if(check)
{
cout <<"Couldn't create thread "<<i<<" Error: "<<check<<endl;
exit(-1);
}
}
//Release all of the blocked threads now that they have all been created
for(int i =1; i<=T_Valve_Numbers;i++)
{
sem_post(&threadCreation);
}
//Make the main process wait for all the threads before terminating
for(int i =1; i<=T_Valve_Numbers;i++)
{
pthread_join(threads[i],NULL);
}
return 0;
}
void* Valve_Handler(void* threadNumArg)
{
int threadNum = *((int *)threadNumArg);
sem_wait(&threadCreation);//Blocks the thread until all are spawned
sem_wait(&tester);
cout<<"I'm thread "<<threadNum<<endl;
sem_post(&tester);
}
当 T_Valve_Numbers = 10 时,一些样本输出为:
Creating thread: 1
Creating thread: 2
Creating thread: 3
Creating thread: 4
Creating thread: 5
Creating thread: 6
Creating thread: 7
Creating thread: 8
Creating thread: 9
Creating thread: 10
I'm thread 11 //Where is 11 coming from?
I'm thread 8
I'm thread 3
I'm thread 4
I'm thread 10
I'm thread 9
I'm thread 7
I'm thread 3
I'm thread 6
I'm thread 6 //How do I have 2 6's?
或
Creating thread: 1
Creating thread: 2
Creating thread: 3
Creating thread: 4
Creating thread: 5
Creating thread: 6
Creating thread: 7
Creating thread: 8
Creating thread: 9
Creating thread: 10
I'm thread 11
I'm thread 8
I'm thread 8
I'm thread 4
I'm thread 4
I'm thread 8
I'm thread 10
I'm thread 3
I'm thread 9
I'm thread 8 //Now '8' showed up 3 times
“我是线程...”打印了 10 次,所以看起来我的信号量让所有线程都通过了。我只是不知道为什么他们的线程数搞砸了。
【问题讨论】:
-
将 I 的值而不是其地址传递给线程。
-
正如我在下面所说的,我必须传递一个类型
void *并且我的编译器不允许我直接从 int 转换。我找不到/想出任何其他方法。
标签: c++ multithreading semaphore