shihyu 发表于 2016-05-12 00:12

使用 pthread_mutex_lock thread 交错

本帖最后由 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[+]

请问这是可能是什么原因造成

谢谢

windoze 发表于 2016-05-12 01:03

本帖最后由 windoze 于 2016-05-12 01:04 编辑

你的代码没有让两个thread“交错”,只是让两个thread不要一起执行lock中间的那行代码而已。

不要假设OS调度线程的方式,它完全可以让一个thread先跑完再跑另一个,完全符合你的代码写出来的行为。
页: [1]
查看完整版本: 使用 pthread_mutex_lock thread 交错