Synchronize struct in C for Threading
I have a global struct that I use within threads, that I create utilizing pthread.h
.
There are concurrent threaded events updating variables within it.
Therefore my data within the struct often is out of sync, as I found out via extensive debugging.
There's no keyword like "synchonized
" (Java background) in C afaik. So how do I block the data-structure to keep it valid?
My struct is:
struct thread_data
{
int nr;
int time;
};
struct thread_data thread_data_array[MAX_THR];
MAX_THR is defined as 10 e.g..
My data get passed to the new thread with pthread_create
:
pthread_create(&threads[num_threads], NULL, Thread_Fkt, &thread_data_array[num_thread]);
Sometimes Threads are created within other threads. There's no linear termination. Does C pr开发者_如何学编程ovide a synchronized set of data-structures?
Thanks ;)
You should probably look into pthread mutex
:
A mutex is a MUTual EXclusion device, and is useful for protecting shared data structures from concurrent modifications, and implementing critical sections and monitors.
Threads are not part of C itself but of the operating system.
The "pthread" in pthread_create
stands for POSIX threads. There are several utilities in POSIX to synchronize between threads. It would certainly depend on what you want to achieve exactly.
pthread_mutex_t
pthread_barrier_t
pthread_cond_t
You can find first information about these by consulting the man pages of their "init" functions, e.g
man pthread_mutex_init
Presumably your num_threads
variable is global and shared between all threads. As an example of using pthreads mutexes, you would protect this variable by declaring an associated mutex:
int num_threads = 0;
pthread_mutex_t mtx_num_threads = PTHREAD_MUTEX_INITIALIZER;
Then whenever you access the variable, you need to take a lock on the mutex:
pthread_mutex_lock(&mtx_num_threads);
new_thread = num_threads++;
pthread_mutex_unlock(&mtx_num_threads);
pthread_create(&threads[new_thread], NULL, Thread_Fkt, &thread_data_array[new_thread]);
I just wanted to clarify the two other answers.
Unlike in other languages, in "C", you can't just declare a structure as "protected" and have the compiler/libraries/framework abstract all the synchronization for you.
pthread mutexes are the way to go, but it is a manual process in which you have to determine which sections of code (as opposed to which data structures) are to be protected, and to put that protection in your code.
This consists of determining which pieces of code would touch these shared data structures, and put the code inside the appropriate pthread_mutex_lock and pthread_mutex_unlock statements.
Mutexes are slow. See if you can get away with atomic operations.
精彩评论