kri*_*tap 3 c concurrency multithreading pthreads
我有以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,字符串"In 1"连续显示10000次,然后"In 2"连续显示10000次,反之亦然.字符串不应该是交替的而不是连续显示在这里吗?
调度程序交错线程的顺序不是确定性的(......它只是从调度程序/内核的角度来看).你不应该对订单做出假设.
在这种情况下,您会遇到其中一个线程被允许在调度程序之前完成其整个工作 - >抢占它并允许另一个线程运行.