我无法让三个线程井井有条
I can not get three threads to be in order
我有三个线程,我想序列化
我正在使用线程是C++。我正在尝试对输出进行排序,以便它将是 {A,B,C,A,B,C,A,B,C,...............}。我这样做是因为我有很多线程想要序列化。我想要的输出是:
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
........
........
这是我拥有的代码。它有时会挂起,有时运行一两个循环,然后挂起。我想听听你对问题的看法。我的代码是:
thread_test.cpp
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition = 0;
int count = 0;
void* thread_c( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition != 2 )
pthread_cond_wait( &cond, &mutex );
printf( "Thread C");
condition = 0;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
void* thread_b( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition != 1 )
pthread_cond_wait( &cond, &mutex );
printf( "Thread B" );
condition = 2;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
void* thread_a( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition != 0 )
pthread_cond_wait( &cond, &mutex );
printf( "Thread A");
condition = 1;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
int main( void )
{
pthread_t thread_a_id;
pthread_create( &thread_a_id, NULL, &thread_a, NULL );
pthread_t thread_b_id;
pthread_create( &thread_b_id, NULL, &thread_b, NULL );
pthread_t thread_c_id;
pthread_create( &thread_c_id, NULL, &thread_c, NULL );
int a = pthread_join(thread_a_id, NULL);
int b = pthread_join(thread_b_id, NULL);
int c = pthread_join(thread_c_id, NULL);
}
要编译代码,我使用
g++ -lpthread -std=gnu++0x thread_test.cpp
问题是pthread_cond_signal()
可以自由选择它想要的任何等待线程,而您的代码取决于它选择特定的线程。
如果我用pthread_cond_broadcast()
替换pthread_cond_signal()
,我无法再让代码停止。我提到这一点是一种观察;我还没有说服自己这是一个正确的解决方案。
撇开为什么要将线程序列化到这种程度的问题不谈,问题是如果多个线程正在等待条件,pthread_cond_signal( &cond )
可能只唤醒其中一个线程来检查条件(实际上这是预期和通常期望的行为 - 如果释放多个服务员,则更像是意外)。
例如,当thread_a()
设置condition = 1
时,它打算唤醒thread_b
。 但是,thread_c
可能与thread_b
同时等待。 使用 pthread_cond_signal
您无法控制将释放哪些thread_b
或thread_c
。
改用pthread_cond_broadcast( &cond )
唤醒所有服务员。
三个条件变量,每个线程一个。线程 A 表示一个线程 B 正在等待表单,谁向一个线程 C 等待,谁发出信号一个线程 A 正在等待......
但是,如果您只打算串行运行它们,那么拥有三个可以并行工作的线程有什么用?
你应该研究一下: 死锁
- 用于矢量处理的多个线程
- 如何在多个线程中创建 QSql数据库连接时防止名称冲突
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 将 10 个线程与原子布尔值同步
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 一个线程等待多个线程事件
- 如果在 2 个线程中使用,是否值得将size_t声明为 std::atomic?
- 餐饮哲学家问题 - 只有 2 个线程工作
- 如果两个线程相互依赖,则 cpp 线程连接应使用连接导致死锁
- std::cout 来自多个线程
- 是否需要 mutex() 来安全地同时访问具有 2 个线程的数组的不同元素?
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 多个线程可以安全地同时将相同的值写入同一变量吗?
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 我无法让三个线程井井有条
- 在 c++ 中退出具有三个线程的两个并发队列
- 创建了三个线程来实例化同一个类.但很快只有一个线程继续运行
- 使用std::memory_order和三个线程的同步谜语