一周总有那么一天是懵逼的,多线程基础。
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *fun()
{
static int flag = 0;
int count = 0;
char *ptr = NULL;
ptr = (char *)malloc(1024);
printf("%p\n", ptr);
}
int main()
{
pthread_t pth;
int i = 0;
int ret = 0;
for(i=0; i<16; i++)
{
ret = pthread_create(&pth, NULL, fun, NULL);
if(ret != 0)
return -1;
pthread_detach(pth);
}
return 0;
}
这是个例子,16个线程,
能共享的是:静态变量 全局变量,堆,
不能共享的:函数参数、局部变量,存在栈上,每个线程都有自己的栈
知道哪些是共享数据,你现在就可以在脑海里平铺一下16个线程了,每个线程都malloc出一块1024字节的内存,调用printf打印就是输出自己线程开辟的首地址。