实现信号量
Implementing a 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,允许多个线程在信号量上调用"wait",而不会将这些线程实际阻塞并放入信号量队列中。
在您的情况下,我会做的是在 main 函数中初始化一个初始值为 NUM_THREADS/2 的信号量。然后我会在 threadedFunction 的开头插入一行,在那里我做一个等待(信号量(,在函数的末尾插入一行,在那里你做一个信号(信号量(。这样,当线程即将退出函数时,它会发出信号,该线程在调用信号量等待后被阻塞,并允许该线程进入。希望这有帮助。
相关文章:
- 删除旧的信号量系统V
- 父进程和子进程之间的 POSIX 信号量
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 多线程.如果我使用信号量,我可以在开始时创建很多线程还是应该只有几个线程?
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- 单车道桥 使用信号量进行同步
- 用于 64 位/32 位 IPC 的 POSIX 信号量的替代方案?
- 这个餐饮哲学家问题(dpp)的解决方案是如何工作的?互斥体和信号量
- 发布信号量返回错误 6(无效句柄)
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 在使用 pthread 和信号量实现生产者-消费者问题时需要帮助
- 实现信号量
- 实现信号量时混淆了核心转储
- 使用互斥锁和信号量实现屏障
- 如何在多核系统上实现信号量
- 用C++实现一个二进制信号量类
- 使用x86程序集的信号量实现
- C ++自己实现信号量
- 我能否仅使用事件、互斥体和信号量实现公平"wait on multiple events"?
- 信号量实现