操作系统-线程创建

14 篇文章 0 订阅
11 篇文章 0 订阅

线程创建

pthread_create

int pthread_create(
pthread_t *thread, //线程ID,为无符号长整型,说明非常大
//非常大的线程ID,为7、8位,进程数为5、4位
//为传出参数
const phread_attr_t *attr, //线程属性,可以设置分里还是不分离
//为NULL表示默认不分离
void *(*start_routine)(void *), //线程处理函数
void *arg //线程处理函数参数,给上面的回调函数传参
);

返回值

成功返回0,失败返回错误号
perror不能够用来打印错误信息

父线程退出之后,地址释放,子线程也没有了。

编译

-l后跟库的名字
-L后跟库的路径
所以,在编译的时候,加上语句
-lpthread

创建一个线程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <pthread.h>	//线程对应的头文件

void* myfunc(void* arg)
{
	//打印子线程的id
	printf ("child thread id: %lu\n", pthread_self());
	return NULL;
}


int main(int argc, const char* argv[])
{
	//创建一个子线程
	//线程ID变量
	pthread_t pthid;
	pthread_creat(&pthid, NULL, myfunc, NULL);
	printf ("parent thread id: %lu\n",pthread_self());

	for (int i=0; i<5; i++)
	{
		printf ("i = %d\n", i);
	}
	sleep(2); //为了让父进程等待子进程
	return 0;
}
创建多个线程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <pthread.h>	//线程对应的头文件

//全局变量的探究
int count = 0;

void* myfunc(void* arg)
{
	//取数据
	int num = *(int *)arg;
	//打印子线程的id
	printf ("%d %dth child thread id: %lu\n", count, num, pthread_self());
	return NULL;
}


int main(int argc, const char* argv[])
{
	//创建多个子线程
	//线程ID变量
	pthread_t pthid[5];
	for (int i=0; i<5; i++)
	{
		//第四个参数采用的是传地址的方式
		//pthread_creat(&pthid[i], NULL, myfunc, (void*)&i);
		// 注意,这里取i的值时都是从栈的地址取值
		//因为线程用的地址都是一样的
		//同理,全局变量也是一样
		//都需要同一块地址
		count = i; 
		//第四个参数采用的是传值,没有影响,
		//因为传递的值是在接下来所要运行的栈空间,所以,不会变乱
		pthread_create(&pthid[i], NULL, mufunc, (void*)i);
		//执行顺序可能乱序,但没关系
	}
	printf ("parent thread id: %lu\n",pthread_self());

	for (int i=0; i<5; i++)
	{
		printf ("i = %d\n", i);
	}
	sleep(2); //为了让父进程等待子进程
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值