0

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);
}
dragosht
  • 3,237
  • 2
  • 23
  • 32
zahra
  • 175
  • 1
  • 10
  • How is the thread going to wait for you to fill up the array? It runs before you fill the array. They run both at the same time. Use pthread_barrier or pthread_mutex to synchronize them. – KamilCuk Sep 25 '18 at 05:52
  • I want them to work at the same time. This is why I created the thread before filling the array. In other words I want the thread to be activated after 100 elements of the array are filled. Does a pthread start working after it is created? @KamilCuk – zahra Sep 25 '18 at 06:24
  • "*Does a pthread start working after it is created?*" sooner or later, yes. – alk Sep 25 '18 at 06:32
  • But your thread needs to wait for the array to be filled. It doesn't. It just checks and exists. Then you start filling the array in your main thread. Craete a pthread_mutex that is locked, and unlock it after you increment args.arg1 to 100. You can check for args.arg1 in a loop, but it may not work and args.arg1 has to be atomic. – KamilCuk Sep 25 '18 at 08:32
  • You might like to take a look at mutex' and conditions. – alk Sep 25 '18 at 13:28

1 Answers1

0

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.

Matt
  • 63
  • 1
  • 8