每日一c pthread_once

#include "../apue.h"


#define MEMORY_SIZE 50//设置一个缓冲区大小事50bty


pthread_once_t once_thread = PTHREAD_ONCE_INIT;
//pthread_once(&once_thread, create_memory);//在多个线程调用,只被一个线程执行,在只开辟一次空间


char *p = NULL;//设置一个全局的指针 并且清空其值


void create_memory(void)//申请内存空间
{
p = malloc(MEMORY_SIZE);//为指针分配50字节的内存空间


printf("mem:%p\n", p);//打印分配指针的地址
return;
}


void *thread_fun(void *arg)//设置一个毁掉函数  
{
char *px = (char *)arg;  //函数调用 参数  并且将void的强转成 char 型  返回给px
//first_thread 0x10 堆
//second_thread 0x20 
//
pthread_once(&once_thread, create_memory);//在多个线程调用,只被一个线程执行,在只开辟一次空间


strcpy(p, px);//将px中的内容拷贝到 p中   px只是作为该函数的一个临时变量


pthread_exit(p);//退出
}
int main()
{
pthread_t thread[2];//申请两个线程的描述符
char *buf[2] ={"hello world.this is pthread 1.\n", "hello student.this is pthread 2.\n"};// 初始化两个buf
char *pret;//初始化一个变量
int i;//申请一个整数变量
/*
1 hello world.
2 hello student.
*/
for(i=0; i<2; i++)
{
pthread_create(thread+i, NULL, thread_fun, buf[i]);//创建线程  将值写入线程
printf("%d  was establish.\n",i+1);
}//创建了两个


for(i=0; i<2; i++)
{
pthread_join(thread[i], (void **)&pret);
printf("%d  was  running  .\n",i+1);
}//调用了两个线程   


printf("%s", pret);

}



output:

hk@hk:/mnt/share/mydemo/newAPUE/10_day$ ./a.out 
1  was establish.
2  was establish.
mem:0x9f9a128
1  was  running  .
2  was  running  .
hello world.this is pthread 1.




























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值