【问题标题】:Can I reuse pthread_t and pthread_attr_t for new diferent thread of already executed thread consecutively?我可以连续重用 pthread_t 和 pthread_attr_t 用于已执行线程的新不同线程吗?
【发布时间】:2020-04-19 07:57:43
【问题描述】:

我想在不使用 pthread_join 的情况下连续执行 2 个不同的线程,可以吗?还是我真的必须像这样声明新的thread_t:

pthread_create(&th,&thread_attr,shtdwn,(void*)&lpBuffer);
pthread_create(&th,&thread_attr,Run,(void*)&args);

而且我也不需要等待任何一个线程完成。 非常感谢您的帮助!

【问题讨论】:

  • 是的,技术上没问题。尽管在实践中,不跟踪每个线程以防它需要被杀死或加入或任何其他线程操作是不寻常的。
  • 如果我在创建线程时删除前 2 个参数是否也有效?因为我不需要等待那些线程完成
  • 等一下。你真的确定你不需要pthread_join吗?至少在某些时候不要调用pthread_join 是不好的做法,因为这可能会导致僵尸线程。此外,如果线程是在主线程中创建的,则主线程必须等待,否则所有线程将在主线程退出时终止。
  • 肯定是的,因为我还有一种方法可以使用传递给线程的地址来终止第一个线程
  • 我不知道你最后的评论是什么意思。但无论如何,关于你之前的问题,pthread_create man page 可以回答他们。如果您乐于使用默认属性值,pthread_attr_t 参数可以为 NULL,但 pthread_t 不能为 NULL。

标签: c multithreading pthreads


【解决方案1】:

pthread_tpthread_attr_t 变量都可以在每个 pthread_create 调用中重复使用。事实上,pthread_attr_t 像这样被重用是很常见的。但是,重用pthread_t 变量有点不寻常,因为该值通常被存储以用于线程上的后续pthread 操作(例如pthread_join)。

此外,pthread_attr_t 可以为 NULL,在这种情况下将使用默认属性。但是,pthread_t 参数不能为 NULL。来自pthread_create manual

attr 参数指向一个 pthread_attr_t 结构,其内容在线程创建时用于确定新的属性 线;该结构使用 pthread_attr_init(3) 初始化,并且 相关功能。如果 attr 为 NULL,则创建线程 默认属性。

在返回之前,成功调用 pthread_create() 会存储 ID 线程指向的缓冲区中的新线程;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多