在C ++中多线程的join()和detach()有什么不同? [英] What is different between join() and detach() for multi threading in C++?

查看:1216
本文介绍了在C ++中多线程的join()和detach()有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中的多线程中, join() detach()有什么区别?
join()删除线程?

What is different between join() and detach() in multi threading in C++? Does join() kill the thread?

推荐答案

一般来说(但并不总是)一个C ++ 线程 c>对象表示一个执行线程,它是一个操作系统或平台的概念。

A C++ thread object generally (but not always) represents a thread of execution, which is an OS or platform concept.

当调用 thread :: join()时,调用线程将阻塞,直到执行线程完成。基本上,这是一个可以用来知道线程何时完成的机制。当 thread :: join()返回时,OS线程的执行已经完成,并且C ++ 线程

When thread::join() is called, the calling thread will block until the thread of execution has completed. Basically, this is one mechanism that can be used to know when a thread has finished. When thread::join() returns, the OS thread of execution has completed and the C++ thread object can be destroyed.

调用 thread :: detach(),执行线程从 code>线程对象,并且不再由线程对象表示 - 它们是两个独立的东西。可以销毁C ++ 线程对象,并且可以继续执行的操作系统线程。如果程序需要知道执行的线程何时完成,需要使用一些其他机制。 不能在线程对象上调用join(),因为它不再与执行线程相关联。

The thread::detach() is called, the thread of execution is "detached" from the thread object and is no longer represented by a thread object - they are two independent things. The C++ thread object can be destroyed and the OS thread of execution can continue on. If the program needs to know when that thread of execution has completed, some other mechanism needs to be used. join() cannot be called on that thread object any more, since it is no longer associated with a thread of execution.

当它仍然是可连接时,销毁C ++ 线程对象被认为是一个错误。也就是说,为了销毁一个C ++ 线程对象,需要调用(和完成) join() detach()必须被调用。如果C ++ 对象在销毁时仍然是可连接的,那么将抛出一个异常。

It is considered an error to destroy a C++ thread object while it is still "joinable". That is, in order to destroy a C++ thread object either join() needs to be called (and completed) or detach() must be called. If a C++ thread object is still joinable when it's destroyed, an exception will be thrown.

一个C ++ 线程对象不代表执行线程(即,可以不可接受):

Some other ways that a C++ thread object will not represent a thread of execution (ie., can be unjoinable):


  • 默认构造的线程对象不代表执行线程,因此不能连接。

  • 已从中移出将不再表示执行的线程,因此不可连接。

  • A default constructed thread object does not represent a thread of execution, so is not joinable.
  • A thread that has been moved from will no longer represent a thread of execution, so is not joinable.

这篇关于在C ++中多线程的join()和detach()有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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