2017-03-27 92 views
0

我在下面有下面的代码。我只想要一半的线程一次输入线程函数。我如何创建一个Semaphore来阻止其他进程?当线程完成使用函数时,我将如何解除先前阻塞的进程?实现信号量

#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

为什么你用'pthread'而不是'std :: thread'和'std :: mutex'? – Xirema

+0

我们的老师在他的例子中使用了pthread,所以我在这个项目中也使用了它。 – Jose

回答

1

你可以做的是使用计数信号量(而不是二进制信号量)。计数信号量的初始值大于1,允许多个线程在信号量上调用“等待”,并且不会将这些线程实际阻塞并放入信号量队列中。

我会在你的情况下做的是在初始值为NUM_THREADS/2的主函数中初始化一个信号量。然后,我会在threadedFunction的开始处插入一行,在此处执行等待(信号量)和函数末尾的一行,在此处执行信号(信号量)。这样,当一个线程即将退出函数时,它会在调用信号量的等待之后发出一个被阻塞的线程信号,并让线程进入。 希望这有帮助。