0

我遇到了多线程同步的问题,我将只发布一个我正在做的“尝试”同步的示例,因为原始代码更大。基本上我有一个附加了 3 个线程的繁重进程,为了锁定/解锁线程,我使用修改每个线程中互斥状态的函数。像这样的东西:

## thread.c ##
    #include "thread.h"

extern int socks;

pthread_mutex_t sem = PTHREAD_MUTEX_INITIALIZER;

void lock()
{
    pthread_mutex_lock(&sem);
}

void unlock()
{
    pthread_mutex_unlock(&sem);
}

void* thread(void* arg)
{
    printf("Socks: %d\n",socks);
    lock();
    lock();

    printf("Unlocked\n");
    return;
}


## main.c ##
#include "defines.h"
#include "thread.h"

int socks;

int main()
{
    pthread_t tid;
    socks= 9;

    pthread_create(&tid, NULL, thread, NULL);

    //sleep(2);
    unlock();
    pthread_join(tid,NULL);
}

执行代码后我得到的是:

。/测试

袜子:9

显然我有一些概念错误,但我找不到问题。线程不应该用 unlock() 解锁?为什么我在解锁调用之前使用 sleep(2) 时程序可以工作?我应该使用哪种方式来避免问题?每个代码都在单独的文件中。

提前致谢!PS:对不起我蹩脚的英语!

4

1 回答 1

0

Since the thread runs asynchronously, it might happen that the main thread joins before the thread has hit the lock. In this case I would suspect that the unlock() just happens too early, and the behaviour you get isn't well defined. If you let the main thread sleep for a while before you unlock, the other thread seems to have time to hit the lock and can be unlocked, resulting in the behaviour you seem to expect.

于 2012-06-29T01:38:57.003 回答