3- 创建线程

参考: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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值