简体   繁体   中英

Writing and reading from a buffer with pthread

I am trying to use pthread. In my code below I have defined two global variables (arg1 and arg2) and in the main function I start filling each element of arg2 with 1. I want the pthread to print the 101-th element of arg2 as soon as it is filled by main. But the pthread prints nothing. Actually the changes of arg1 is not followed by pthread and the pthread assumes that arg1 is 0. How can I activate a pthread so that when I write in a buffer in main, the pthread starts reading from buffer simultaneously?

Thanks in advance.

#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);
}

The thread is terminated by the time you get to the for loop. arg1 is still not initialized in ProcessThread . You can use a while loop with the sleep function to test periodically the condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM