加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

pthreads和并发

发布时间:2020-12-20 12:21:40 所属栏目:Python 来源:网络整理
导读:我有以下代码: #include pthread.h#include stdio.h#include stdlib.h#define LOOPS 10000void *run(void *arg){ int id = strtol(arg,NULL,0); int i; for(i=0; iLOOPS; i++) { printf("In %d.n",id); }}int main(){ pthread_t p1,p2; void *res; pthread
我有以下代码:

#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,run,"1");
    pthread_create(&p2,"2");
    pthread_join(p1,&res);
    pthread_join(p2,&res);
    return 0;
}

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

解决方法

调度程序交错线程的顺序不是确定性的(……它只是从调度程序/内核的角度来看).你不应该对订单做出假设.

在这种情况下,您会遇到其中一个线程被允许在调度程序之前完成其整个工作 – >抢占它并允许另一个线程运行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读