线程创建
#include <stdio.h>
#include <pthread.h>
// 线程的工作函数
void *worker(void *v)
{
long num = (long)v;
while (1)
{
printf ("子线程: %ld\n", num);
sleep(1);
}
}
int main()
{
// 1、创建的线程的id,是一个传出参数
// 2、线程属性 ---> 一般为NULL
// 3、线程的工作函数,线程创建成功后,从该函数开始执行
// 4、给工作函数传的参数
pthread_t thread;
int ret = pthread_create(&thread, NULL, worker, (void*)10);
if (0 != ret)
{
printf ("创建线程失败\n");
return -1;
}
while (1)
{
printf ("主线程: %d\n", 123);
sleep(1);
}
return 0;
}
线程结束
#include <stdio.h>
#include <pthread.h>
// 线程的工作函数
void *worker(void *v)
{
// while (1)
{
printf ("子线程id: %ld\n", pthread_self());
sleep(5);
}
long num = 10;
// return (void *)num;
// return "hello";
pthread_exit("hello");
}
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, worker, NULL);
// long sum;
// pthread_join(thread, (void**)&sum);
char *buf;
pthread_join(thread, (void**)&buf);
printf ("主线程 处理了 一个线程, 返回值:%s\n", buf);
// printf ("主线程 处理了 一个线程, 返回值:%ld\n", sum);
return 0;
}
线程结束处理
#include <stdio.h>
#include <pthread.h>
// 线程的工作函数
void *worker(void *v)
{
// while (1)
{
printf ("子线程id: %ld\n", pthread_self());
sleep(5);
}
printf ("子线程退出\n");
}
// 线程结束处理:
// 1、调用 pthread_join 回收线程资源
// 2、使用线程分离,将线程的资源回收工作交给系统
// 3、当主线程调用 pthread_exit() 不影响其他线程执行,进程当所有线程都结束以后才推出
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, worker, NULL);
pthread_detach(thread); // 线程分离
printf("asdsadsa\n");
pthread_exit(NULL); // 主线程结束运行
return 0;
}