2014-02-17 4 views
0

코드의 주석에 내 문제를 작성했습니다.Posix Pthread 상호 배제

pthread를 사용하여 코드를 병렬 처리하려고합니다. 먼저 여러 스레드에서 병렬로 대량의 데이터를 메모리에 쓰려고합니다. 데이터를 쓰고 나자이 데이터를 같은 스레드로 실행하려고합니다. 그리고 데이터를 실행 한 후에 읽고 싶습니다. 그리고이 세 가지 작업 후에이 데이터를 다른 파일로 전달하려고합니다. 그리고이 과정을 여러 번 반복하고 싶습니다.

정말 감사드립니다. 감사합니다.

#include <pthread.h> 
#include <stdio.h> 

#define ARRAYSIZE 100 
#define NUMTHREADS 7 

struct ThreadData { 
    int start, stop, id; 
    int* array; 
}; 

/* function to write, execute and read data */ 
void* cal(void* td) { 
    struct ThreadData* data=(struct ThreadData*) td; 
    int start=data->start; 
    int stop=data->stop; 
    int thread_id = data ->id; 
    int i,s, counter; 
    counter = 0; 

    //main loop 
    for (s=0; s<200; s++){ 

     // in this loop1, I want to write data here by all the threads 
     for (i=start; i<stop; i++) { 
    printf("thread %d is writing data\n", thread_id); 
     } 

     //in this loop2, after data written by all the threads in loop1, 
     // data is execuated by all threads in this loop2 
     for (i=start; i<stop; i++) { 
    printf("thread %d is executing data\n", thread_id); 
     } 

     //in this loop3, data is read after completion of 
     // writing and execution in loop1 and loop2 
     for (i=start; i<stop; i++) { 
    printf("thread %d is reading data\n", thread_id); 
     } 

     // counter, I want this counter to be executed only once 
     // per iteration after writing, executing and reading data. 
     counter = counter +1; 
    printf ("Value of counter is %d\n", counter); 

    } 

    return NULL; 
} 

int main(void) { 
    int array[ARRAYSIZE]; 
    pthread_t thread[NUMTHREADS]; 
    struct ThreadData data[NUMTHREADS]; 
    int i; 

    int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS; 

    /* Divide work for threads, prepare parameters */ 
    for (i=0; i<NUMTHREADS; i++) { 
     data[i].start=i*tasksPerThread; 
     data[i].stop=(i+1)*tasksPerThread; 
     data[i].array=array; 
     data[i].id = i; 
    } 
    /* the last thread must not go past the end of the array */ 
    data[NUMTHREADS-1].stop=ARRAYSIZE; 

    /* Launch Threads */ 
    for (i=0; i<NUMTHREADS; i++) { 
     pthread_create(&thread[i], NULL, cal, &data[i]); 
    } 

    /* Wait for Threads to Finish */ 
    for (i=0; i<NUMTHREADS; i++) { 
     pthread_join(thread[i], NULL); 
    } 

    return 0; 
} 
+0

나는 세마포어 (http://www.csc.villanova.edu/~mdamian/threads/posixsem.html)를 사용하여 그렇게 할 수 있다고 생각한다. –

+0

하지만 내 의견으로는 각 루프마다 다른 스레드를 사용해야한다. –

+0

독서에 대해 상호 배제가 필요 없음을 알아 두십시오. –

답변

1

난 당신이 그렇게하기 전에 스레드 동기화 단계를 수행에만 카운터 상호 배제를 필요가 있다고 생각하고 그것으로 충분해야한다.

관련 문제