等待通知pthreads unix C++
Wait notify pthreads unix C++
我有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);
}
}
相关文章:
- 在UNIX系统中使用DIR查找文件的字节大小
- 当套接字连接断开时检测C/C++Unix
- C++:floor unix时间戳到UTC月份
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 外壳包装器句柄/执行交互式命令管道C++ UNIX
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- createFile() 和 DeviceIoControl() 等效于 Unix/Linux 中的卷设备
- 如何将 jsoncpp 库包含在 unix 上的项目中?
- 如何"buffer" UNIX 信号
- 从Qt上的UNIX域套接字(QLocalSocket)读取
- 为什么对于gcc来说,"UNIX"和"unix"宏不是一回事?
- 如何设置Qt应用程序以使用类Unix系统的实际环境变量?
- 将带斜杠的 Unix 路径转换为 Windows 路径
- 将 unix 时间戳转换为人类可读的日期
- 从ubuntu上的utc时间计算unix时间
- 在UNIX中通过recv/send交换数据时,如何正确使用缓冲区
- 避免 unix 中的标准库冲突
- 使特定于Unix的CMake过程跨平台
- 如何在 C++ (UNIX) 中完全阻止用户输入
- C++:将Unix时间转换为非本地时区