在本教程中,我们将讨论一个程序,以了解C / C ++中的线程函数。
线程函数允许用户同时实现并发功能,这些并发功能可以相互依赖执行或独立执行。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* func(void* arg){
//分离当前线程
pthread_detach(pthread_self());
printf("在线程内部\n");
pthread_exit(NULL);
}
void fun(){
pthread_t ptid;
//创建一个新线程
pthread_create(&ptid, NULL, &func, NULL);
printf("该行可能在线程终止之前被打印\n");
if(pthread_equal(ptid, pthread_self())
printf("线程相等\n");
else
printf("线程不相等\n");
//等待创建的线程终止
pthread_join(ptid, NULL);
printf("线程结束后将打印此行\n");
pthread_exit(NULL);
}
int main(){
fun();
return 0;
}输出结果
该行可能在线程终止之前被打印 线程不相等 在线程内部 线程结束后将打印此行