参考:https://blog.csdn.net/choudan8888/article/details/98329862
创建线程接口:pthread_create() 创建成功返回0,否则返回非零值
通过示例简单了解下线程执行情况
注意:
1- Makefile脚本加上-lpthread,不然报错
2- main函数中创建完线程后一定要让出线程,比如sleep(),否则新创建的线程得不到执行。
示例:
#Makeile
main:main.o
gcc main.o -o main -lpthread
main.o:main.c
gcc -c -Wall main.c -o main.o
.PHONY:clean
clean:
rm -rf *.o main
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>
void * thread_strat(void *message)
{
printf("%s[%d] %s\n thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
/*让出执行权,返回main。直到main再次让出执行权*/
sleep(1);
printf("%s[%d] thread=%lu here is thread\n",__func__,__LINE__,pthread_self());
return message;
}
int main(void)
{
pthread_t thread;
int ret;
const char *message = "creat thread succ";
/*只是创建线程,并不执行*/
ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
if(!ret)
{
perror("pthread_creat");
}
printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
/*让出执行权,开始执行线程。直到线程睡眠,才返回main*/
sleep(1);
printf("%s[%d] thread=%lu i'm comming!\n",__func__,__LINE__,pthread_self());
sleep(1);
printf("%s[%d] thread=%lu i'm comming!\n",__func__,__LINE__,pthread_self());
return 0;
}