每次运行以下代码时,它都会看起来是随机的,我不明白为什么有时它会打印某些行,而有时则不会。
使用clang -Wall -lpthread test.c
#include <stdio.h>
#include <pthread.h>
int var = 2;
pthread_t my_thread;
pthread_mutex_t lock;
void* thread_func(void *args);
void thread_func2();
void* thread_func(void *args) {
pthread_mutex_lock(&lock);
printf("Entered thread_func\n");
fflush(stdout);
pthread_mutex_unlock(&lock);
thread_func2();
pthread_mutex_lock(&lock);
printf("Exiting thread_func\n");
fflush(stdout);
pthread_mutex_unlock(&lock);
return NULL;
}
void thread_func2() {
pthread_mutex_lock(&lock);
printf("Entering thread_func2\n");
fflush(stdout);
pthread_mutex_unlock(&lock);
for(int i = 0; i < var; i++) {
pthread_mutex_lock(&lock);
printf("Var = %d.\n", i);
fflush(stdout);
pthread_mutex_unlock(&lock);
}
pthread_mutex_lock(&lock);
printf("Exiting thread_func2\n");
fflush(stdout);
pthread_mutex_unlock(&lock);
}
int main(int argc, char** argv) {
int status;
status = pthread_create(&my_thread, NULL, thread_func, NULL);
pthread_mutex_lock(&lock);
printf("Status = %d\n", status);
pthread_mutex_unlock(&lock);
}
这是连续七次执行的输出:
ssh.server.connected.to 219% a.out
Status = 0
Entered thread_func
Entered thread_func
Entering thread_func2
Var = 0.
Var = 1.
Exiting thread_func2
Exiting thread_func2
Exiting thread_func
ssh.server.connected.to 220% a.out
Status = 0
Entered thread_func
Entered thread_func
ssh.server.connected.to 221% a.out
Status = 0
Entered thread_func
Entered thread_func
ssh.server.connected.to 222% a.out
Status = 0
Entered thread_func
Entered thread_func
ssh.server.connected.to 223% a.out
Status = 0
Entered thread_func
Entered thread_func
ssh.server.connected.to 224% a.out
Status = 0
Entered thread_func
Entered thread_func
ssh.server.connected.to 225% a.out
Status = 0
Entered thread_func
答案 0 :(得分:1)
您的主线程没有等待子线程退出。退出主线程也会杀死所有子线程。所以它是竞争条件,因此产生的行为是不确定的。
在pthread_join
中添加main
电话,等待子线程退出。