I am fairly new in threads programming and I wanted to test the mutex functionality. So I programmed the following in order to test it.
**thread_test.h
...
extern int flags;
extern pthread_mutex my_mutex;
...
**thread_test.c
...
#include"thread_test.h"
...
void * thread_test(void *thread_parameters)
{
long tid = (long) thread_parameters;
pthread_mutex_lock(&my_mutex);
++flags;
printf("**THREAD %d** started. Flag value is %d.\n",tid, flags);
sleep(6);
pthread_mutex_unlock(&my_mutex);
pthread_exit(NULL);
}
...
**main.c
...
#include"thread_test.h"
...
#define THREADS 5
pthread_t threads[THREADS];
pthread_mutex_t my_mutex;
int flags = 0;
...
int main(){
int rct;
for(rct = 0; rct<THREADS; rct++)
if(pthread_create(&threads[rct],NULL, thread_test, (void *)rct))
printf("ERROR!")
else
{
sleep(1);
printf("Thread %d initialised in main and the flags value is %d.\n", rct,flags);
}
pthread_mutex_destroy(&my_mutex);
...
It appears that even though I lock the mutex in the child threads, the main program somehow overwrites the mutex lock while a thread has it and assigns variable flags with a new value..
Does anyone have an idea why this is happening?
From what I see you have several errors in your code, part of which your compiler should have told you if you switch all warnings on.
pthread_mutex_t
variables must be initialized. For static initialization using = PTHREAD_MUTEX_INITIALIZER
at the point of defininition would be enough. (And there is not much point in destroying a static mutex on the other end.)
in the code snippet you gave there is no declaration of thread_test
visible to main
you exit main
(and destroy the mutex) before the threads have terminated. You may do this, but then you'd have to use an explit pthread_exit
in main
(and definitively don't do the destroy then). The commonly used approach is not to do this, but to use pthread_join
for all threads that have been created.
Also, you could indent your code before posting here, that would much help to make it more readable.
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.