#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);
#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.