【发布时间】:2013-09-30 18:56:51
【问题描述】:
我是多线程的新手。 当我运行以下程序时,它的输出为
Function1
Function2
1000...1001
但是当我调试程序时,它会按预期输出。
1000...1001
Function1
Function2
所以,我认为在直接运行时(无需调试)模式会出现一些同步问题。但有一件事让我很困惑,我使用的是mutex,那么为什么会出现同步问题?
请帮帮我。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
pthread_mutex_t myMutex;
void * function1(void * arg);
void * function2(void * arg);
void * function0(void * arg);
int count = 0;
const int COUNT_DONE = 10;
main()
{
pthread_t thread1, thread2, thread0;
pthread_mutex_init(&myMutex, 0);
pthread_create(&thread0, NULL, &function0, NULL );
pthread_create(&thread1, NULL, &function1, NULL );
pthread_create(&thread2, NULL, &function2, NULL );
pthread_join(thread0, NULL );
pthread_join(thread1, NULL );
pthread_join(thread2, NULL );
pthread_mutex_destroy(&myMutex);
return 0;
}
void *function1(void * arg)
{
cout << "Function1\n";
}
void *function0(void *arg)
{
int i, j;
pthread_mutex_lock(&myMutex);
for (i = 0; i <= 1000; i++)
{
for (j = 0; j <= 1000; j++)
{
}
}
cout << i << "..." << j << endl;
pthread_mutex_unlock(&myMutex);
}
void *function2(void * arg)
{
cout << "Function2\n";
}
【问题讨论】:
-
空循环有什么用?编译器可能会删除它们。另外,请解释互斥锁应该如何强制排序
-
@Leeor:Mtex 用于同步目的!
-
您不应该同时在
function2和function1上使用互斥锁吗? -
@RasmiRanjanNayak - 仅在正确使用的情况下...
-
@nims:现在我在这两个函数中都加入了互斥锁。但结果是相同的没有改变
标签: c++ multithreading synchronization pthreads mutex