无法理解线程的行为

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] );

除此之外,你似乎误解了线程的作用。线程用于并行执行计算。您可以有效地将它们一个接一个地同步运行,除了额外的问题之外什么也没有得到。