重用的pthread_t变量当前正在运行的线程 [英] reusing pthread_t variable for currently running threads

查看:402
本文介绍了重用的pthread_t变量当前正在运行的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我升技不确定的,如果下面的code会导致不确定的行为。

I'm abit uncertain if the following code will lead to undefined behavior.

//global
pthread_t thread1;

void *worker(void *arg){
  //do stuff
}


void spawnThread(){
  //init stuff
  int iret1 = pthread_create( &thread1, NULL, worker, (void*) p);
}

我spawnThread将使用全局线程1做一个新的线程。

My spawnThread will make a new thread using the global thread1.

如果我目前运行的是没有完成一个线程,使用线程1变量开始一个新的线程时将我莫名其妙地导致未定义的行为?

If I'm currently running a thread that is not finished, will I somehow cause undefined behaviour when starting a new thread using the thread1 variable?

如果这是一个问题,它将使意义,使我的pthread_t局部变量的函数吗?我想是因为它会使用堆栈,只要我从我的功能将被删除返回它可能是问题。

If this is a problem, would it make sense to make my pthread_t variable local to a function? I think it might be problem because it will use the stack, and as soon as i return from my function that will be removed.

如果我让我的pthread_t函数的局部,我不能在我的程序的其他部分使用pthread_join函数。是典型的解决方案,能有多少当前线程正在运行的mutex'ed计数器保持跟踪?

If I make my pthread_t local to a function, I can't use the pthread_join in a another part of my program. Is the canonical solution, to have a mutex'ed counter keeping track of how many current threads are running?

感谢

推荐答案

的pthread_t 只是一个标识符。您可以复制圆,或随意摧毁它。当然,你提到,如果你破坏它(因为它是本地的),那么你不能用它来调用在pthread_join

The pthread_t is just an identifier. You can copy it round or destroy it at will. Of course, as you mention, if you destroy it (because it is local) then you cannot use it to call pthread_join.

如果您重复使用多个线程,然后在同一个的pthread_t 变量除非只有一个线程同时有效要覆盖用新的旧的价值观,和你只能叫在pthread_join 最近启动的线程上。另外,如果你是从多个线程内开始你的线程,那么你将需要保护的pthread_t 变量用互斥锁。

If you reuse the same pthread_t variable for multiple threads then unless there is only one thread active at a time you are overwriting the older values with the new ones, and you will only be able to call pthread_join on the most recently started thread. Also, if you are starting your threads from inside multiple threads then you will need to protect the pthread_t variable with a mutex.

如果你需要等待你的线程来完成,给它自己的的pthread_t 变量,并调用在pthread_join 点在哪里,你需要等待。如果您不需要等待你的线程完成,叫 pthread_detach()创建之后,或使用创建属性来启动线程分离。

If you need to wait for your thread to finish, give it its own pthread_t variable, and call pthread_join at the point where you need to wait. If you do not need to wait for your thread to finish, call pthread_detach() after creation, or use the creation attributes to start the thread detached.

这篇关于重用的pthread_t变量当前正在运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆