【发布时间】:2019-01-01 20:13:17
【问题描述】:
我有这个非常简单的代码:
void *myfunc (void *variable);
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
char *msg1 = "First thread";
char *msg2 = "Second thread";
int ret1, ret2;
ret1 = pthread_create(&thread1, NULL, myfunc, (void *) msg1);
ret2 = pthread_create(&thread2, NULL, myfunc, (void *) msg2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("First thread ret1 = %d\n", ret1);
printf("Second thread ret2 = %d\n", ret2);
return 0;
}
void *myfunc (void *variable)
{
char *msg;
msg = (char *) variable;
printf("%s\n", msg);
}
这是我一直得到的结果:
Second thread
First thread
First thread ret1 = 0
Second thread ret2 = 0
在我之前创建的第一个线程的代码中,但第二个线程似乎运行第一个线程。据我所知,您无法控制哪个线程首先运行,但我已经多次运行程序,使用“for”循环,结果总是相同,看起来并不随机。有什么方法可以确保我创建的第一个线程首先运行?
【问题讨论】:
-
线程彼此独立运行。创建它们后,您将无法控制它们的启动顺序或运行方式。如果您需要线程以特定顺序运行,则需要使用同步原语(如条件变量或信号量等)明确指定该顺序。
-
另外,
ret1和ret2变量仅包含pthread_create调用的成功/失败,而不是线程“返回”的内容 -
也许还要想想“任意”、“不可预测”、“随机”和“依赖于实现”的区别。无论如何,最终,您根本不能依赖任何特定的行为。