简体   繁体   English

线程没有并行运行

[英]Threads not running parallel

I want to make parallel threads. 我想制作并行线程。 Example: my output is like: thread1 thread3 thread4 thread2... In main: 示例:我的输出如下:thread1 thread3 thread4 thread2 ...在main中:

pthread_t tid;
int n=4;
int i;
for(i=n;i>0;i--){
    if(pthread_create(&tid,NULL,thread_routine,&i)){
        perror("ERROR");
    }
    pthread_join(tid,NULL);
}

And my function(routine) is: 我的功能(例程)是:

void *thread_routine(void* args){
    pthread_mutex_lock(&some);
    int *p=(int*) args;
    printf("thread%d ",*p);
    pthread_mutex_unlock(&some);
}

I always got result not parallel: thread1 thread2 thread3 thread4. 我总是得到不平行的结果:thread1 thread2 thread3 thread4。 I want this threads running in same time - parallel. 我希望这些线程在同一时间运行 - 并行。 Maybe problem is position pthread_join, but how can I fix that? 也许问题是位置pthread_join,但我该如何解决?

You want to join the thread after you have kicked off all of the threads. 在您启动所有线程后,您想要加入该线程。 What your code currently does is starts a thread, then joins, then starts the next thread. 你的代码目前所做的是启动一个线程,然后加入,然后启动下一个线程。 Which is essentially just making them run sequentially. 这实际上只是让它们按顺序运行。

However, the output might not change, because that happens based solely on whichever thread gets to the lock first. 但是,输出可能不会更改,因为这仅基于首先获得锁定的任何线程。

Yes, the join is preventing any of the threads from running concurrently, because it is blocking the main thread from continuing creating other threads until the just-created thread terminates. 是的,连接阻止任何线程同时运行,因为它阻止主线程继续创建其他线程,直到刚刚创建的线程终止。 Remove the join and they should run concurrently. 删除连接,它们应该同时运行。 (Though possibly still not parallel depending on your system.) (虽然可能仍然不平行,具体取决于您的系统。)

However, you might not see any difference in your output. 但是,您可能看不到输出的任何差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM