• 正文
  • 相关推荐
申请入驻 产业图谱

飞凌嵌入式ElfBoard-线程的创建与终止之创建和终止线程示例

06/21 15:34
200
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

1.示例:创建和终止线程

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

void *thread_function(void *arg) {

printf("Thread is running\n");

int *result = malloc(sizeof(int));

*result = 42; // 返回值

pthread_exit(result); // 结束线程并返回结果

}

int main() {

pthread_t thread;

void *result;

// 创建线程

if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {

perror("Failed to create thread");

return 1;

}

// 等待线程结束

if (pthread_join(thread, &result) != 0) {

perror("Failed to join thread");

return 1;

}

// 获取线程返回值

printf("Thread exited with value: %d\n", *((int *)result));

free(result); // 释放内存

return 0;

}

2.运行结果

Thread is running

Thread exited with value: 42

3.代码解析

先定义了一个线程函数thread_function,在函数中,打印一条消息,表示线程正在运行;随后动态分配一个整数大小的内存块,并将其地址赋给指针 result。这个指针用于存储线程的返回值。将值 42 存储在刚刚分配的内存中,作为线程的返回值;使用 pthread_exit(result) 结束当前线程。主函数中调用pthread_create创建一个线程,然后使用pthread_join()等待线程结束,最后释放之前给result分配的内存。

相关推荐