2012-04-15 48 views
8

我有一个很大的问题,我不明白为什么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

我不明白这东西是如何工作的。请帮忙!

回答

16
pthread_create(&mythread, NULL, func, NULL); 
pthread_create(&mythread, NULL, anotherFunc, NULL); 

pthread_mutex_destroy(&mymutex); 

你销毁互斥之前线程都用它做,所以所有的赌注都关闭。在破坏它之前,您可能会想要2个线程pthread_join

+0

我认为它的工作原理:) 这是我的兴趣的人最终代码... http://pastebin.me/bc23773578d79a55882d7ced4e04b026 – 2012-04-15 11:12:15

+0

还是坏了。当你销毁互斥锁​​时,你只确保*一个*线程已经完成。如果另一个还没完成呢?无法保证线程将启动,获取互斥锁,或以任何特定顺序完成,除非您以某种方式强制它。 (多线程课程之一是这样的:只有当你强制按照特定顺序发生时,才会确保事物发生。) – 2012-04-15 11:13:39

+0

是的,但是我的两个函数都在一个线程中启动,唯一的线程是mythread。 可以这么做吗?或者为一个功能使用一个线程总是比较安全? – 2012-04-15 11:20:23

2

我有几个comiplation错误

  • 我不能宣布INT I循环

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

我已经使用pthread_join在之前破坏了互斥锁。

这样我摧毁两个线程“功能”和“anotherFunc”后,我的互斥体“mymutex”已经完成了其执行

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

#include <stdlib.h> 
#include <stdio.h> 
#include <pthread.h> 

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; 
}