我是多线程的新手。当我运行下面的程序时,它给出的输出为
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";
}