當前位置:成語大全網 - 新華字典 - c語言怎麽創建線程和使用

c語言怎麽創建線程和使用

1、添加線程相關的頭文件:#include<pthread.h>

2、線程創建函數是pthread_create()函數,該函數的原型為:

int?pthread_create(pthread_t?*thread,pthread_attr_t?*attr,void*?(*start_routine)(void*),void?*arg);

3、線程退出函數是pthread_exit()函數,該函數的原型為:

void?pthread_exit(void?*retval);

創建線程的示例程序如下:

/*

**程序說明:創建線程函數pthread_create()函數的使用。

*/

#include?<stdio.h>

#include?<pthread.h>

#include?<unistd.h>

#include?<stdlib.h>

#include?<string.h>

//打印標識符的函數

void?print_ids(const?char?*str)

{

pid_t?pid; //進程標識符

pthread_t?tid; //線程標識符

pid=getpid(); //獲得進程號

tid=pthread_self(); //獲得線程號

printf("%s?pid:%u?tid:%u?(0x%x)\n",

str,(unsigned?int)pid,(unsigned?int)tid,(unsigned?int)tid);?//打印進程號和線程號

}

//線程函數

void*?pthread_func(void?*arg)

{

print_ids("new?thread:"); //打印新建線程號

return?((void*)0);

}

//主函數

int?main()

{

int?err;

pthread_t?ntid; //線程號

err=pthread_create(&ntid,NULL,pthread_func,NULL); //創建壹個線程

if(err?!=?0)

{

printf("create?thread?failed:%s\n",strerror(err));

exit(-1);

}

print_ids("main?thread:"); //打印主線程號

sleep(2);

return?0;

}