[英]Implementing a Semaphore
我下面有以下代码。 我只希望一半的线程一次进入threadedfunction。 如何创建信号量以阻止其他进程? 每当线程完成使用该函数后,我将如何解开以前阻塞的进程?
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 4
long int sharedcount;
pthread_mutex_t count_mutex;
//Function that will be run by multiple threads
//Needs to return a void pointer and if it takes arguments
//it needs to be a void pointer
void *ThreadedFunction(void *threadid)
{
int success;
long id = (long)threadid;
//Lock mutex preventing the other threads from ru nning
success = pthread_mutex_lock( &count_mutex );
cout << "Thread " << id << " beginning.\n";
for(int i = 0; i < 100000000; i++)
sharedcount++;
cout << "Thread " << id << " exiting.\n";
cout << sharedcount << endl;
//Unlock the mutex after the thread has finished running
pthread_mutex_unlock( &count_mutex );
//Kill the thread
pthread_exit(NULL);
}
int main ()
{
//Initialize mutex
pthread_mutex_init(&count_mutex, NULL);
//Create an array of threads
pthread_t threads[NUM_THREADS];
int rc;
int i;
sharedcount = 0;
for( i=0; i < NUM_THREADS; i++ )
{
cout << "main() : creating thread, " << i << endl;
//Create thread by storing it in a location in the array. Call the
//function for the threads to run inside. And pass the argument (if any).
//If no arguments pass NULL
rc = pthread_create(&threads[i], NULL, ThreadedFunction, (void *)i);
if (rc)
{
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
//Have main thread wait for all other threads to stop running.
for(i = 0; i < NUM_THREADS; i++)
pthread_join(threads[i], NULL);
//cout << sharedcount << endl;
pthread_exit(NULL);
}
您可以使用计数信号量(而不是二进制信号量)。 计数信号量的初始值大于1,允许多个线程在信号量上调用“等待”,而实际上没有阻塞那些线程并将其放入信号量队列。
在您的情况下,我将在main函数中使用NUM_THREADS / 2的初始值初始化一个信号量。 然后,我将在threadedFunction的开头插入一行,在其中执行wait(信号灯),在函数的末尾插入一行,然后执行信号(信号灯)。 这样,当一个线程即将退出该函数时,它会发出信号,该线程在对信号量进行调用后被阻塞,并允许该线程进入。希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.