使用pthread

时间:2018-09-25 05:38:55

标签: c linux pthreads pthread-join pthread-barriers

我正在尝试使用pthread。在下面的代码中,我定义了两个全局变量(arg1和arg2),在主函数中,我开始用1填充arg2的每个元素。我希望pthread在填充arg2时立即打印第101个元素主要。但是pthread不会打印任何内容。实际上,arg1的更改没有跟随pthread,并且pthread假定arg1为0。我如何激活pthread,以便当我在main中写入缓冲区时,pthread同时开始从缓冲区读取?

谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#include <pthread.h>


struct arg_struct {
    int arg1;
    int arg2[1000];
};

//volatile int arg1;

//int arg2[1000];

void *ProcessThread (void *arguments){
    struct arg_struct *args = arguments;

    if( args -> arg1==100) {
        printf("%d",  args -> arg2[ args -> arg1]);
    }
    pthread_exit(NULL);
    return NULL;
}

void main(){
    struct arg_struct args;

    pthread_t thread1;
    void *thread_status;
    pthread_create(&thread1, NULL, ProcessThread, (void *)&args);

    for ( args.arg1=0; args.arg1<1000; args.arg1++){
        args.arg2[args.arg1] =1;
    }
    pthread_join(thread1,&thread_status);
}

1 个答案:

答案 0 :(得分:0)

线程在到达for循环时终止。 arg1仍未初始化ProcessThread。您可以使用带有睡眠功能的while循环来定期测试条件。

相关问题