我有一个很大的问题,我不明白为什么C中的互斥锁不能按我的预期工作。 这是我的代码:POSIX C线程。互斥体的例子。不按预期工作
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
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“功能”的消息,然后100“anotherFunc”消息的程序。我期望的是执行达到func并锁定互斥锁。当执行到达另一个函数时,我希望等到func解锁这个互斥量。但我得到的消息干扰像
FUNC FUNC FUNC anotherFunc anotherFunc anotherFunc FUNC anotherFunc
我不明白这东西是如何工作的。请帮忙!
我认为它的工作原理:) 这是我的兴趣的人最终代码... http://pastebin.me/bc23773578d79a55882d7ced4e04b026 – 2012-04-15 11:12:15
还是坏了。当你销毁互斥锁时,你只确保*一个*线程已经完成。如果另一个还没完成呢?无法保证线程将启动,获取互斥锁,或以任何特定顺序完成,除非您以某种方式强制它。 (多线程课程之一是这样的:只有当你强制按照特定顺序发生时,才会确保事物发生。) – 2012-04-15 11:13:39
是的,但是我的两个函数都在一个线程中启动,唯一的线程是mythread。 可以这么做吗?或者为一个功能使用一个线程总是比较安全? – 2012-04-15 11:20:23