Sonu Mishra Sonu Mishra - 4 months ago 16
C Question

Threads not acting on global variable

I have a huge multi-threaded code base. There are 100 threads. 99 threads have a function

do_thread_operations
associated with each of them. 100th thread has an operation
monitor_99threads
associated with it.

do_thread_operations
have infinite loop, so they never stop.
monitor_99threads
keeps track of time. One minute after it was started, it has to close all 99 threads and return to the main thread.

Following is my code.

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

int *to_close_thread;

void * do_thread_operations(void * thread_data){
int i = *(int *)thread_data;
while (1){
//do something
if (to_close_thread[i]) break;
}
}

void * monitor_99threads(void * data){
int i = 0;
while(1){
i++;
if(i > 60){
for (int i = 0; i < 99; ++i){
printf("Closing %d", i);
to_close_thread[i] = 1;
}
}
}
}

int main(){
to_close_thread = (int *)malloc(99 * sizeof(int));
memset(to_close_thread, 0, 99*sizeof(int));
pthread_t threads[100];
for (int i = 0; i < 99; ++i){
int j = i;
pthread_create(&threads[i], NULL, do_thread_operations, (void *)&j);
}
pthread_create(&threads[99], NULL, monitor_99threads, NULL);
for (int i = 0; i < 100; ++i){
pthread_join(threads[i], NULL);
}

}


Problem is that although closing prints, the threads do not break out of their loops.

Answer

Here,

  for (int i = 0; i < 99; ++i){
        int j = i;
        pthread_create(&threads[i], NULL, do_thread_operations, (void *)&j);
    }

You are passing the address of j, which has block scope and has auto storage duration. You should something like:

    int arr[100] = {0}; /* adjust the number or allocate using malloc as per needs */
    for (int i = 0; i < 99; ++i){
        arr[i] = i;
        pthread_create(&threads[i], NULL, do_thread_operations, &arr[i]);
    }

Another problem is your monitor thread doesn't break after sending closing message. As it is, it's running in an infinite loop. You probably need a break; statement when (whatever) condition is met.

Comments