让主程序等待线程完成

发布于 2024-11-17 03:55:57 字数 911 浏览 0 评论 0原文

在下面的代码中,我创建了一定数量的线程,每个线程都会休眠几秒钟。

然而,我的主程序不会等待线程完成,我假设线程将继续运行,直到它们自行完成。

即使调用线程完成,是否有某种方法使线程继续运行。

#include <pthread.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>


int sample(int min,int max){
  int r=rand();
  return (r %max+min );
}



void *worker(void *p){
  long i = (long) p;
  int s = sample(1,10);
  fprintf(stdout,"\tid:%ld  will sleep: %d \n",i,s);
  sleep(s);
  fprintf(stdout,"\tid:%ld  done sleeping \n",i,s);
}

pthread_t thread1;

int main(){
  int nThreads = sample(1,10);

  for(int i=0;i<nThreads;i++){
    fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
    int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
    pthread_detach(thread1);
  }
  //  sleep(10);//work if this is not commented out.
  return 0;
}

谢谢

编辑:

抱歉没有澄清,是否可以在不明确跟踪我当前正在运行的线程并使用 join.

In the following code I create some number of threads, and each threads sleeps for some seconds.

However my main program doesn't wait for the threads to finish, I was under the assumption that threads would continue to run until they finished by themselves.

Is there someway of making threads continue to run even though the calling thread finishes.

#include <pthread.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>


int sample(int min,int max){
  int r=rand();
  return (r %max+min );
}



void *worker(void *p){
  long i = (long) p;
  int s = sample(1,10);
  fprintf(stdout,"\tid:%ld  will sleep: %d \n",i,s);
  sleep(s);
  fprintf(stdout,"\tid:%ld  done sleeping \n",i,s);
}

pthread_t thread1;

int main(){
  int nThreads = sample(1,10);

  for(int i=0;i<nThreads;i++){
    fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
    int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
    pthread_detach(thread1);
  }
  //  sleep(10);//work if this is not commented out.
  return 0;
}

Thanks

Edit:

Sorry for not clarifying, is it possible without explicitly keeping track of my current running threads and by using join.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

青巷忧颜 2024-11-24 03:55:57

每个程序都有一个主线程。它是 main() 函数执行的线程。当该线程的执行完成时,程序及其所有线程也将完成。如果您希望主线程等待其他线程,则必须使用 pthread_join 功能

Each program has a main thread. It is the thread in which your main() function executes. When the execution of that thread finishes, the program finishes along with all its threads. If you want your main thread to wait for other threads, use must use pthread_join function

别低头,皇冠会掉 2024-11-24 03:55:57

您需要跟踪线程。您没有这样做,因为您正在创建的每个线程都使用相同的 thread1 变量。

您可以通过创建传递给 pthread_create() 函数的 pthread_t 类型列表(或数组)来跟踪线程。然后你pthread_join()列表中的那些线程。

编辑:

嗯,你真的很懒,不跟踪正在运行的线程。但是,您可以通过在线程结束之前增加一个全局变量(受互斥锁保护)来实现您想要的目的。然后在主线程中,您可以检查该 var 是否达到您想要的值。在示例代码中输入nThreads

You need to keep track of the threads. You are not doing that because you are using the same thread1 variable to every thread you are creating.

You track threads by creating a list (or array) of pthread_t types that you pass to the pthread_create() function. Then you pthread_join() those threads in the list.

edit:

Well, it's really lazy of you to not keep track of running threads. But, you can accomplish what you want by having a global var (protected by a mutex) that gets incremented just before a thread finishes. Then in you main thread you can check if that var gets to the value you want. Say nThreads in your sample code.

无人接听 2024-11-24 03:55:57

您需要加入您创建的每个线程:

int main()
{
    int                    nThreads = sample(1,10);
    std::vector<pthread_t> threads(nThreads);

    for(i=0; i<nThreads; i++)
    {
            pthread_create( &threads[i], NULL, worker, (void*) i)
    }

    /* Wait on the other threads */
    for(i=0; i<nThreads; i++)
    {
            status*   status;
            pthread_join(threads[i], &status);
    }
}

You need to join each thread you create:

int main()
{
    int                    nThreads = sample(1,10);
    std::vector<pthread_t> threads(nThreads);

    for(i=0; i<nThreads; i++)
    {
            pthread_create( &threads[i], NULL, worker, (void*) i)
    }

    /* Wait on the other threads */
    for(i=0; i<nThreads; i++)
    {
            status*   status;
            pthread_join(threads[i], &status);
    }
}

你知道你的假设是错误的。主要是特别。退出 main 会杀死你的线程。所以有两个选择:

  1. 使用pthread_exit退出main。此函数将允许您退出 main,但保持其他线程运行。

  2. 做一些事情来保持 main 的存活。这可以是任何东西,从循环(愚蠢且低效)到任何阻塞调用。 pthread_join 很常见,因为它会阻塞,但如果您感兴趣的话,还会为您提供线程的返回状态,并清理死线程资源。但为了防止 main 终止,任何阻塞调用都会执行,例如选择、读取管道、阻塞信号量等。

由于 Martin 展示了 join(),这里是 pthread_exit()< /代码>:

int main(){
  int nThreads = sample(1,10);

  for(int i=0;i<nThreads;i++){
    fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
    int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
    pthread_detach(thread1);
  }

  pthread_exit(NULL);
}

You learned your assumption was wrong. Main is special. Exiting main will kill your threads. So there are two options:

  1. Use pthread_exit to exit main. This function will allow you to exit main but keep other threads running.

  2. Do something to keep main alive. This can be anything from a loop (stupid and inefficient) to any blocking call. pthread_join is common since it will block but also give you the return status of the threads, if you are interested, and clean up the dead thread resources. But for the purposes of keeping main from terminating any blocking call will do e.g. select, read a pipe, block on a semaphore, etc.

Since Martin showed join(), here's pthread_exit():

int main(){
  int nThreads = sample(1,10);

  for(int i=0;i<nThreads;i++){
    fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
    int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
    pthread_detach(thread1);
  }

  pthread_exit(NULL);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文