In my test program, I run two threads, each of which performs the following logic:
1) pthread_mutex_lock() 2) sleep(1) 3) pthread_mutex_unlock()
However, I found that after some time one of the two threads will be blocked on pthread_mutex_lock () forever, and the other thread is working fine. This is a very strange behavior, and I think it can be a serious problem. When using pthread_mutex_t with the Linux manual, sleep () is not prohibited. So my question is: is this a real problem or are there any errors in my code?
The following is a test program. In the code, the output of the first stream is directed to stdout, and the second to stderr. Therefore, we can check these two different outputs to see if the thread is blocked.
I tested it on the linux kernel (2.6.31) and (2.6.9). Both results are the same.
//======================= Test Program =========================== #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <pthread.h> #define THREAD_NUM 2 static int data[THREAD_NUM]; static int sleepFlag = 1; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void * threadFunc(void *arg) { int* idx = (int*) arg; FILE* fd = NULL; if (*idx == 0) fd = stdout; else fd = stderr; while(1) { fprintf(fd, "\n[%d]Before pthread_mutex_lock is called\n", *idx); if (pthread_mutex_lock(&mutex) != 0) { exit(1); } fprintf(fd, "[%d]pthread_mutex_lock is finisheded. Sleep some time\n", *idx); if (sleepFlag == 1) sleep(1); fprintf(fd, "[%d]sleep done\n\n", *idx); fprintf(fd, "[%d]Before pthread_mutex_unlock is called\n", *idx); if (pthread_mutex_unlock(&mutex) != 0) { exit(1); } fprintf(fd, "[%d]pthread_mutex_unlock is finisheded.\n", *idx); } } // 1. compile // gcc -o pthread pthread.c -lpthread // 2. run // 1) ./pthread sleep 2> /tmp/error.log
This is the conclusion:
On the terminal where the program is running:
root@skyscribe :~
On another terminal, to see the /tmp/error.log file
root@skyscribe :~
And no new lines are output from / tmp / error.log