2014-02-17 167 views
0

我在代碼的註釋中寫了我的問題。Posix Pthread互斥

我想通過使用pthreads使我的代碼並行。 首先,我想通過多個線程並行地在內存中寫入大量數據。 寫入數據後,我想通過相同的線程執行這些數據。 在執行數據後,我想閱讀它。 這三個操作之後,我想將這些數據傳遞給其他文件。 我想多次重複這個過程。

我真的很感激你的任何幫助。 謝謝。

#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

我想你需要互斥僅供計數器,以便做之前,線程同步步驟,這應該是足夠的。