Linux多线程2-1---创造新线程

一、线程的ID

1577241661392

pthread_t:结构体(FreeBSD5.2、Mac OS10.3)/unsigned long int(linux)
/usr/include/bits/pthreadtypes.h

获取线程ID:pthread_self()
一个实例:获取主线程ID

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "include/pthread.h"

#ifndef _WIN64
#pragma comment(lib,".\\lib32\\pthreadVC2.lib")
//#pragma comment(lib,".\\lib32\\pthreadVCE2.lib")
//#pragma comment(lib,".\\lib32\\pthreadVSE2.lib")
#else
#pragma comment(lib,".\\lib64\\pthreadVC2.lib")
#endif // !
int main()
{
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();

    printf("pid is %u, tid is %x\n", pid, tid);

    return 0;
}

二、创造新线程

int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg)
第一个参数:新线程的id,如果成功则新线程的id回填充到tidp指向的内存
第二个参数:线程属性(调度策略,继承性,分离性…)
第三个参数:回调函数(新线程要执行的函数)
第四个参数:回调函数的参数
返回值:成功返回0,失败则返回错误码
编译时需要连接库libpthread

实例:创建线程,打印ID
程序框图

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "include/pthread.h"

/*
在window下使用的BUG解决
C2011 “timespec”:“struct”类型重定义
解决方法:
在pthread.h中

#if !defined( PTHREAD_H )
#define PTHREAD_H
下面加上
#define HAVE_STRUCT_TIMESPEC
*/



#ifndef _WIN64
#pragma comment(lib,".\\lib32\\pthreadVC2.lib")
//#pragma comment(lib,".\\lib32\\pthreadVCE2.lib")
//#pragma comment(lib,".\\lib32\\pthreadVSE2.lib")
#else
#pragma comment(lib,".\\lib64\\pthreadVC2.lib")
#endif // !

/*
*getpid()          获取进程ID
*pthread_self()    获取ID
*
*int pthread_create(pthread_t *thread,
*                     const pthread_attr_t *attr,
*                     void *(*start_routine) (void *),
*                 void *arg);
*第一个参数,新线程id,创建成功系统回填
*第二个参数,新线程到属性,NULL为默认属性
*第三个参数,新线程到启动函数
*第四个参数,传递给新线程
*/

void print_id(char*s )
{
	pthread_t tid;

	tid = pthread_self();
	printf("%s tid is 0x%x\n", s, tid);
}
void *thread_fun(void *arg)
{
	print_id((char*)arg);
	return (void *)0;
}


int main()
{
	/*
	//测试连接是否正确
	//pid_t pid;  //进程ID
	pthread_t tid;  //线程ID
	//pid = getpid();
	tid = pthread_self();
	printf("pid is , tid is %x\n",tid);
	*/



	pthread_t ntid;
	int err;
	
	err = pthread_create(&ntid, NULL, thread_fun, "new thread");
	if (err!=0)
	{
		printf("create new thread failed\n");
		return 0;
	}

	print_id("main thread :");
	Sleep(2);

	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值