1 线程的创建、终止 1.1 创建线程 通过pthread_create()函数创建线程,函数定义如下: int pthread_create(pthread_t * thread , pthread_attr_t const* attr , void * (*start_routine)(void *) , void * arg) ; 返回值:若是成功建立线程返回0,否则返回错误的编号 参数:thread 要创建的线程的线程id指针 ...
retval:pthread_exit()调用线程的返回值,可由其他函数如pthread_join来检索获取。 1. 2. 3. 4. 5. 6. 7. 8. 2、pthread_join函数 intpthread_join(pthread_t thread,void**value_ptr);函数pthread_join的作用是,等待一个线程终止。 调用pthread_join的线程,将被挂起,直到参数thread所代表的线程终止时为止。
在主线程中,等待线程结束后,从共享变量中获取返回值。 下面是一个简单的示例代码: #include <iostream> #include <pthread.h> // 共享变量 int result; // 线程函数 void* threadFunc(void* arg) { int* presult = static_cast<int*>(arg); // 计算返回值 *presult = 42; pthread_exit(NULL); } ...
在Linux中,使用pthread_join()函数可以等待一个线程完成执行并获取其返回值 #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *my_thread(void *arg) { int *result = (int *)arg; *result = 42; // 设置线程返回值 return NULL; } int main() { pthread_t thread_id; int r...
首先,函数pthread_exit(void *retval) 这里的retval就是线程退出的时候返回给主线程的值,也是今天需要讨论的情况。 例子如下: 1 #include <pthread.h> 2 #include <stdio.h> 3 #include <string.h> 4 #include <unistd.h> 5 #include <errno.h> ...
首先看看线程的连接属性,我们通过man命令查看一下pthread_join的文档 int pthread_join(pthread_t thread, void **retval); 参数thread 就是传入线程的ID 参数retval 就是传入线程的返回码,如果线程被取消,那么rval被重置为PTHREAD_CANCELED, 如果调用成功,返回0,失败就返回大于0的整数。
1、线程 创建线程的函数并不会返回线程的状态,线程状态的返回需要借助一个函数,即pthread_exit函数。这个函数可以把在线程内部把线程的退出信息发送到主线程。 而主线程需要用一段空间来存储这个子线程退出时候的状态,因此需要在主线程中提前定义一个变量 ,通过pthread_join函数,来接受到线程的退出状态。例如创建一个...