无法理解pthread行为

时间:2015-09-12 05:42:41

标签: c++ multithreading pthreads

我正在尝试用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个sempahores,每个线程一个,并用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;
}

1 个答案:

答案 0 :(得分:2)

count大于2时,这将失败:

sem_wait( &sem[count] );

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

相关问题