gpt4 book ai didi

c - pthreads和并发

转载 作者:太空狗 更新时间:2023-10-29 15:49:00 24 4
gpt4 key购买 nike

我有以下代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define LOOPS 10000

void *run(void *arg)
{
int id = strtol(arg,NULL,0);
int i;
for(i=0; i<LOOPS; i++)
{
printf("In %d.\n",id);
}
}

int main()
{
pthread_t p1,p2;
void *res;

pthread_create(&p1,NULL,run,"1");
pthread_create(&p2,NULL,run,"2");
pthread_join(p1,&res);
pthread_join(p2,&res);
return 0;
}

当我运行它时,字符串“In 1”连续显示 10000 次然后“In 2”连续显示 10000 次,反之亦然。字符串不应该像这里那样交替显示而不是连续显示吗?

最佳答案

线程被调度程序交错的顺序不是确定的(......好吧,但仅从调度程序/内核的角度来看)。您不应该对订单做出假设。

这种情况中,您会遇到允许其中一个线程在调度程序之前完成其全部工作 -> 抢占它并允许另一个线程运行。

关于c - pthreads和并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com