2017-03-27 95 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的開始處插入一行,在此處執行等待(信號量)和函數末尾的一行,在此處執行信號(信號量)。這樣,當一個線程即將退出函數時,它會在調用信號量的等待之後發出一個被阻塞的線程信號,並讓線程進入。 希望這有幫助。