POSIX C线程。 互斥的例子。 不要按预期工作

我有一个大问题,我无法弄清楚为什么C中的互斥量不能像我期望的那样工作。 这是我的代码:

#include  #include  #include  pthread_t mythread; pthread_mutex_t mymutex; void *anotherFunc(void*) { pthread_mutex_lock(&mymutex); for(int i = 0; i < 100; i++) printf("anotherFunc\n"); pthread_mutex_unlock(&mymutex); pthread_exit(NULL); } void *func(void*) { pthread_mutex_lock(&mymutex); for(int i = 0; i < 100; i++) printf("func\n"); pthread_mutex_unlock(&mymutex); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_mutex_init(&mymutex, NULL); pthread_create(&mythread, NULL, func, NULL); pthread_create(&mythread, NULL, anotherFunc, NULL); pthread_mutex_destroy(&mymutex); pthread_exit(NULL); return EXIT_SUCCESS; } 

我期望发生的是打印前100个“func”消息然后打印100个“anotherFunc”消息的程序。 我期望执行到达func并锁定互斥锁。 当执行到达anotherFunc时,我希望等到func解锁互斥锁。 但我得到了干扰的消息

func func func anotherFunc anotherFunc anotherFunc func anotherFunc

我不明白这件事是如何起作用的。 请帮忙!

 pthread_create(&mythread, NULL, func, NULL); pthread_create(&mythread, NULL, anotherFunc, NULL); pthread_mutex_destroy(&mymutex); 

你在线程完成之前就破坏了互斥锁,所以所有的赌注都是关闭的。 您可能希望在销毁之前pthread_join 2个线程。

我得到了很少的编辑错误

  • 我无法在for循环中声明int i

  • 使用参数名称arg作为线程“func”和“anotherFunc”的参数

销毁互斥锁之前使用过pthread_join

这样,在线程“func”和“anotherFunc”完成执行后,我正在销毁我的互斥锁“mymutex”

此外,每个线程现在都有自己的线程ID “mythread1”“mythread2”,所以这样我就可以为每个线程使用pthread_join()函数

 #include  #include  #include  pthread_t mythread1, mythread2; pthread_mutex_t mymutex; void *anotherFunc(void *arg) { pthread_mutex_lock(&mymutex); int i; for(i = 0; i < 100; i++) printf("anotherFunc\n"); pthread_mutex_unlock(&mymutex); pthread_exit(NULL); } void *func(void *arg) { pthread_mutex_lock(&mymutex); int i; for(i = 0; i < 100; i++) printf("func\n"); pthread_mutex_unlock(&mymutex); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_mutex_init(&mymutex, NULL); pthread_create(&mythread1, NULL, func, NULL); pthread_create(&mythread2, NULL, anotherFunc, NULL); pthread_join(mythread1, NULL); pthread_join(mythread2, NULL); pthread_mutex_destroy(&mymutex); return EXIT_SUCCESS; }