我有这个非常简单的代码:
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”循环多次运行了该程序,并且结果始终相同,看起来也不是随机的。有什么方法可以确保我首先创建的线程先运行?
答案 0 :(得分:0)
有什么办法可以确保我创建的线程首次运行 首先?
当然可以。将第一个线程之后的其他线程序列化为一个信号量(省略错误检查):
auto& Fnc1() { return someNonLocalVariable; }