首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Posix Pthread互斥

Posix Pthread互斥
EN

Stack Overflow用户
提问于 2014-02-17 18:23:08
回答 1查看 511关注 0票数 0

我已经在代码的注释中写下了我的问题。

我正在尝试通过使用pthread来使我的代码并行。首先,我想通过多个线程并行地在内存中写入大量数据。在写入数据之后,我希望通过相同的线程来执行这些数据。在执行完数据后,我想要读取它。在这三个操作之后,我希望将此数据传递给其他文件。我想重复这个过程几次。

我真的很感谢你的帮助。谢谢。

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2014-02-18 02:54:14

我认为只有计数器需要互斥,所以在它之前做一个线程同步步骤,这应该就足够了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21826376

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档