c++ - 实现信号量

标签 c++ multithreading 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,允许多个线程在信号量上调用“等待”,而不是让这些线程实际阻塞并放入信号量队列。

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

关于c++ - 实现信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43036839/

相关文章:

c - 厕所 key 示例中二进制信号量和互斥量之间的区别?

快速信号量命令行工具项目等待组完成

c++ - 为什么字符串连接宏不适用于这个 "+"案例?

c - Linux 中的物理位置感知用户空间内存分配(内存 Controller 亲和性)

Android - 线程与 AlarmManager

c# - 如何让任务等待相同的结果?

c# - 信号量如何从另一个线程中释放?

c++ - 按下按钮后如何停止后台循环?

c++ - 将 boost::bind 与 boost::function 一起使用:检索绑定(bind)变量类型

C++ : can I do some processing before calling another constructor?