gpt4 book ai didi

c++ - 等待通知 pthreads unix C++

转载 作者:行者123 更新时间:2023-11-28 02:05:01 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

请务必阅读 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: %d\n",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: %d\n",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: %d\n",count);
}

pthread_mutex_unlock( &count_mutex );

if(count >= COUNT_DONE) return(NULL);
}

}

关于c++ - 等待通知 pthreads unix C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37855557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com