【嵌入式八股5】C++:多线程相关
1. 线程创建与管理
1.1 pthread_create
- 功能: 创建一个新的线程,并指定该线程的执行函数。
- 参数:
pthread_t *thread
: 指向线程标识符的指针。const pthread_attr_t *attr
: 线程属性,通常为NULL
。void *(*start_routine)(void *)
: 线程执行的函数指针。void *arg
: 传递给线程函数的参数。
- 返回值: 成功返回 0,失败返回错误码。
- 示例:
#include <pthread.h> #include <iostream> void* threadFunc(void* arg) { std::cout << "Thread is running!" << std::endl; return NULL; } int main() { pthread_t thread; if (pthread_create(&thread, NULL, threadFunc, NULL) != 0) { std::cerr << "Failed to create thread!" << std::endl; return 1; } pthread_join(thread, NULL); return 0; }
1.2 pthread_join
- 功能: 主线程等待指定线程终止,并回收其资源。
- 参数:
pthread_t thread
: 要等待的线程标识符。void **retval
: 存储线程返回值的指针,可以为NULL
。
- 返回值: 成功返回 0,失败返回错误码。
- 注意: 如果不调用
pthread_join
,线程资源可能无法释放,导致内存泄漏。
1.3 pthread_detach
- 功能: 将线程设置为分离状态,线程终止后自动释放资源。
- 参数:
pthread_t thread
: 要分离的线程标识符。
- 返回值: 成功返回 0,失败返回错误码。
- 注意: 分离后的线程无法被
pthread_join
等待。
1.4 pthread_cance
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
嵌入式八股/模拟面试拷打 文章被收录于专栏
一些八股模拟拷打Point,万一有点用呢