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
}
线程参数,传地址使用动态分配吧,你只用一个buffer,后面的很可能就把前面的给覆盖了。把所有的输出printf使用一个互斥的信号量同步一下就行了吧,C的标准库不是线程安全的。