Linux系统——多线程编程pthread_join()

Linux系统——多线程编程pthread_join() pthread_exit()

实现代码

#include<bits/stdc++.h>
#include<unistd.h>
#include<pthread.h>
using namespace std;

void* write(void *arg) {
	printf("Write into buffer\n");
	string *buffer = new string("Content");
	return (void*) buffer;
}

void* read(void *arg) {
	pthread_t threadId1;
	string *buffer;
	printf("Read from buffer\n");
	if (pthread_create(&threadId1, NULL, write, NULL)) {
		printf("Create error!\n");
		abort();
	}
	if (pthread_join(threadId1, (void**) &buffer)) {
		printf("Join error!\n");
		abort();
	}
	cout << *(string*) buffer << endl;
	return 0;
}

int main(int argc, char const *arg[]) {
	pthread_t threadId2;
	if (pthread_create(&threadId2, NULL, read, NULL)) {
		printf("Create error!\n");
		abort();
	}
	if (pthread_join(threadId2, NULL)) {
		printf("Join error!\n");
		abort();
	}
	return 0;
}

输出结果

Read from buffer
Write into buffer
Content

实现内容

  • 主线程
    主线程创建子线程,执行read函数,并调用调用pthread_join()函数等待子进程read执行结束
  • 子进程read
    创建子进程,执行write函数,调用pthread_join()函数等待子进程执行并获取返回值,输出write线程的返回值
  • 子进程write
    动态开辟变量buffer并返回其指针给线程read

注意

  • 编译过程
g++ -pthread pthreadCreateTest.cpp -o pthreadParameterTest
./pthreadParameterTest

pthread_join()

  • 返回值
    成功则返回0,否则返回错误代码
  • 函数声明
    int pthread_join(pthread_t thread, void **retval);
  1. 参数thread返回新建线程的ID
  2. 参数retval返回进程函数返回值

pthread_exit()

  • 无返回值
  • 函数声明
    void pthread_exit(void* retval);
    参数retval为线程执行函数的返回值,返回给调用pthread_join()的线程,返回到pthread_join()函数中的retval二级指针中

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
发布了39 篇原创文章 · 获赞 25 · 访问量 3370

猜你喜欢

转载自blog.csdn.net/qq_44486439/article/details/105726803