等待通知pthreads unix C++

Wait notify pthreads unix C++

本文关键字:C++ unix pthreads 通知 等待      更新时间:2023-10-16

我有n个线程,每个线程都修改一个对象O(k),其中k可以是0到n-1。

现在有一个监听器线程l,当任何线程k修改了它的对象O(k)时,它需要得到一个警报

实现这种情况的最快方法是什么?

正如一位评论者已经建议的那样,使用Posix(或者更好的std C++)条件变量。您可以使用相关的互斥锁来保护std::标志数组,每个工作线程一个标志。当工作线程修改其对象时,它会获取互斥并提升其标志。当侦听线程收到通知时,它将为第k:th个对象(对应于数组中的第k:th个标志)提供服务并降低该标志,然后释放互斥对象。

请务必阅读condvars的示例,以便了解何时自动获取/释放互斥对象。

一般来说,std C++线程原语更容易使用,因为它们使用例如RAII来自动解锁互斥等。也可移植到非Posix环境。但下面是的pthreads示例

http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t count_mutex     = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  condition_var   = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int  count = 0;
#define COUNT_DONE  10
#define COUNT_HALT1  3
#define COUNT_HALT2  6
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &functionCount1, NULL);
pthread_create( &thread2, NULL, &functionCount2, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Final count: %dn",count);
exit(EXIT_SUCCESS);
}
// Write numbers 1-3 and 8-10 as permitted by functionCount2()
void *functionCount1()
{
for(;;)
{
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
// Wait while functionCount2() operates on count
// mutex unlocked if condition varialbe in functionCount2() signaled.
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %dn",count);
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
// Write numbers 4-7
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < COUNT_HALT1 || count > COUNT_HALT2 )
{
// Condition of if statement has been met. 
// Signal to free waiting thread by freeing the mutex.
// Note: functionCount1() is now permitted to modify "count".
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %dn",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}