linux下线程
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
pthread_once_t once = PTHREAD_ONCE_INIT; //指定参数位只执行一次
void run(void) //示例线程函数
{
printf("function run is runing in thread %d\n",pthread_self());
}
void *thread1(void *arg)
{
pthread_t thid = pthread_self(); //接受并且打印当前线程的ID
printf("current thread id is %d\n",thid); //调用执行线程函数只执行一次,接受一个标志参数和一个目标函数的指针
pthread_once(&once,run);
printf("thread1 ends\n"); //打印函数调用结束提示信息
}
void *thread2(void *arg)
{
pthread_t thid = pthread_self(); //接受并且打印当前线程ID
printf("current thread is ID %u\n",thid);
pthread_once(&once,run); //调用函数同上以一个函数结构,但是这里并不会成功调用因为只执行一次
printf("thread2 ends\n"); //打印函数调用结束信息
}
int main()
{
pthread_t thid1,thid2; //定义两个线程ID
pthread_create(&thid1,NULL,thread1,NULL); //创建线程,调用上边的函数1和函数2
pthread_create(&thid2,NULL,thread2,NULL);
sleep(3); //主线程(进程)暂停3秒后继续执行
printf("main thread exit!\n");
exit(0);
}
run 函数在线程thread1 中只运行了一次,虽然thread2也调用了,然而并没有什么用
typedef struct
{
int detachstate; 线程的分离状态
int schedpolicy; 线程调度策略
struct sched_param schedparam; 线程的调度参数
int inheritsched; 线程的继承性
int scope; 线程的作用域
size_t guardsize; 线程栈末尾的警戒缓冲区大小
int stackaddr_set;
void * stackaddr; 线程栈的位置
size_t stacksize; 线程栈的大小
}pthread_attr_t;
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void assisthread(void *arg) //示例线程函数
{
printf("i am nothing helping to do some thing\n");
sleep(3); //暂停三秒
//pthread_exit(0);
//线程结束
exit(0);
}
int main()
{
pthread_t assisthid;
int status ;
pthread_create(&assisthid,NULL,(void *)assisthread,NULL); //创建线程
pthread_join(assisthid,(void *)&status); //等待指定线程结束
printf("assistthread's exit is caused %d\n",status);
return 0;
私有数据:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
pthread_key_t key; //定义全局变量,键
void *thread2(void *arg) //第二个函数
{
int tsd = 5; //自己线程的私有数据
printf("thread %d is runing \n",pthread_self());
pthread_setspecific(key,(void *)tsd); //设置一个私有数据
printf("thread %d return %d\n",pthread_self(),pthread_getspecific(key));
}
void *thread1(void *arg)//创建线程一然后调用函数二创建另一个线程
{
int tsd = 0;
pthread_t thid2;
printf("thread %d is runing\n",pthread_self());
pthread_setspecific(key,(void *)tsd);
pthread_create(&thid2,NULL,thread2,NULL);
sleep(5);
printf("thread %d return %d\n",pthread_self(),pthread_getspecific(key));
}
int main()
{
pthread_t thid1;
printf("main thread begins running\n");
pthread_key_create(&key,NULL); //创建一个键
pthread_create(&thid1,NULL,thread1,NULL); //调用函数一创建线程1
sleep(3);
pthread_key_delete(key); //删除键
printf("main thread exit\n");
return 0;
}
最终打印的值一个是5 一个是0,足见这是各个线程私有的数据。