无法理解线程的行为
Not able to understand pthread behaviour
本文关键字:线程 更新时间:2023-10-16
我正试图学习编程与pthreads,这里是一个问题,我试图解决。我有一个数组,假设有10个输入,我有3个线程,我希望每个线程从数组中读取一个项目,直到数组耗尽。
int arr[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
我希望这3个线程的工作方式如下:
T1 T2 T3 T1 T2
10 11 12 13 14
我所尝试的是,我已经采取了3个信号量,每个线程一个,初始化第一个为1,另一个为0,一旦我们创建线程,所有线程将尝试获得他们的信号量,两个线程有sem值初始化为0将不得不等待,一个值为1将得到做的工作。一旦第一个完成,它将发送给第二个,当第二个完成时,它将发送给第三个,以此类推,直到遍历数组中的所有元素。
然而,当我尝试运行以下程序时,它出现了分段错误。我不知道发生了什么事。谁能给我指点一下我做错了什么吗?我写的代码如下所示:
//Read one element using one thread
#include<pthread.h>
#include <semaphore.h>
#include <iostream>
using namespace std;
int arr[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
sem_t sem[3];
int count = 0;
void * printNumbers( void * arg ) {
while(1) {
sem_wait( &sem[count] );
cout<< " Waiting on the semaphore number " << count << endl;
count += 1;
if( count > 9 )
break;
cout<< " consuming " << arr[count]<< " with thid " << * ( (int*) arg ) << endl;
int nextPost = count % 3;
cout<< " Posting to semaphore number " << nextPost << endl;
sem_post( &sem[nextPost] );
}
}
int main() {
sem_init( &sem[0], NULL, 1 );
sem_init( &sem[1], NULL, 0 );
sem_init( &sem[2], NULL, 0 );
int t1 = 0;
int t2 = 1;
int t3 = 2;
pthread_t thid[3];
pthread_create( &thid[0], NULL, printNumbers, &t1 );
pthread_create( &thid[1], NULL, printNumbers, &t2 );
pthread_create( &thid[2], NULL, printNumbers, &t3 );
pthread_exit( 0 );
return 0;
}
当count
大于2时,此操作将失败:
sem_wait( &sem[count] );
除此之外,你似乎误解了线程的作用。线程用于并行执行计算。您可以有效地将它们一个接一个地同步运行,除了额外的问题之外什么也没有得到。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?