- 论坛徽章:
- 1
|
本帖最后由 shihyu 于 2016-05-12 00:12 编辑
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- static pthread_mutex_t Cmtx = PTHREAD_MUTEX_INITIALIZER;
- void* ap1_thread(void* args)
- {
- while (1) {
- pthread_mutex_lock(&Cmtx);
- printf("ap1_thread[+]\n");
- pthread_mutex_unlock(&Cmtx);
- sleep(1);
- }
- return NULL;
- }
- void* ap2_thread(void* args)
- {
- while (1) {
- pthread_mutex_lock(&Cmtx);
- printf("ap2_thread[-]\n");
- pthread_mutex_unlock(&Cmtx);
- sleep(1);
- }
- return NULL;
- }
- int main(int argc, char* argv[])
- {
- pthread_t thread1, thread2;
- pthread_create(&thread1, NULL, ap1_thread, NULL);
- pthread_create(&thread2, NULL, ap2_thread, NULL);
- pthread_join(thread1, NULL);
- pthread_join(thread2, NULL);
- return 0;
- }
复制代码 我起两个 thread 测试交错打印
pthread_mutex_unlock 之后过故意sleep(1) 让另一条thread 可以先lock
这样应该是
ap1_thread[+]
ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
不断交错
, 可是我测试结果会出现有连续印两个ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
ap1_thread[+]
请问这是可能是什么原因造成
谢谢 |
|