一、线程的ID
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;
}