简体   繁体   中英

How to make global variables that are contained in a different class thread safe in c

I have to files one called main.c and one called disperse.c

disperse.c creates threads to handle the load in main.c and looks something like this:

void *entry(void *arg) {  
    foo_function()  
}

void disperse() {  
    pthread_t thread;  
    pthread_create(&thread, NULL, entry, (void*) args);  
    pthread_join(thread, NULL);  
}

main.c contains foo_function() and the function edits global variables. Is there any way to make the global variables contained in main.c thread safe?

In general, it is best to avoid global variables unless you absolutely cannot do what you are trying to do otherwise. With pthreads, thread safety is dependent on the function. Not all of the pthreads functions are "thread safe" on shared data. You can also use thread mutexes to protect shared data. These are essentially a type of lock on a piece of shared data, that only allows one thread to access it at a time. This article gives a good introduction to this: https://randu.org/tutorials/threads/#protect

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