给定以下内容:
pthread_t thread;
pthread_create(&thread, NULL, function, NULL);
pthread_create
函数对thread
做了什么?thread
在加入主线程并终止后会发生什么?如果在
thread
已经加入后,执行以下操作会发生什么:
pthread_create(&thread, NULL, another_function, NULL);
给定以下内容:
pthread_t thread;
pthread_create(&thread, NULL, function, NULL);
pthread_create
函数对thread
做了什么?
thread
在加入主线程并终止后会发生什么?
如果在thread
已经加入后,执行以下操作会发生什么:
pthread_create(&thread, NULL, another_function, NULL);
pthread_create
函数是一个创建线程的函数,它会返回一个值用于标识新创建的线程。如果创建成功,该值将填充thread
参数。如果创建失败,则调用后thread
的值未定义。(参考:http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html)
当线程加入到主线程并终止后,对象本身不会发生任何变化,但它所持有的值不再引用任何线程(因此,您无法将其传递给需要pthread_t
的函数,如果您不小心这样做,可能会出现ESRCH
错误)。
如果在线程已经加入后,您执行了pthread_create
,那么和之前一样:如果创建成功,将分配一个值来标识新创建的线程。
thread
对象的影响,而不是它对被该对象标识的执行线程的影响。 - Steve Jessoppthread_create会使用操作系统调用创建一个线程。抽象的优势在于您不需要关心正在发生什么。它将设置变量“ thread”等于标识符,该标识符可用于引用该线程。例如,如果您有多个线程并想取消其中一个,请使用正确的pthread_t标识符调用
pthread_cancel(thread)
以指定您感兴趣的线程。
当线程加入主线程并终止后,线程会发生什么?
在线程终止之前,变量“ 线程”作为获取或标识线程的键/索引。在线程终止之后,键/索引指向的值不再需要有效。您可以保留它并尝试重用它,但这几乎肯定会导致错误。
如果线程加入后,您这样做会发生什么:
pthread_create(&thread, NULL, another_function, NULL);
pthread_join
不会修改对象。该对象是不透明的。你不能(也不应该)知道每个调用对传递作为参数的 pthread_t
对象做了什么。你只知道它用于标识其他 pthread_*
调用中的线程。 - Martin Yorkpthread_join
通过值传递其pthread_t
参数;它不能影响其值。它肯定可以修改pthread_t
值所标识的“对象”,但这是一个单独的问题,而且Paul的答案甚至从未提到过。这就像free
不修改其传递的指针一样。 - Rob Kennedy