linux 线程总结

来源:互联网 发布:开源交换机网管软件 编辑:程序博客网 时间:2024/06/04 08:46

1、同一进程线程的共享资源

a. 堆  由于堆是在进程空间中开辟出来的,所以它是理所当然地被共享的;
b. 全局变量 它是与具体某一函数无关的,所以也与特定线程无关;因此也是共享的
c. 静态变量虽然对于局部变量来说,它在代码中是“放”在某一函数中的,但是其存放位置和全局变量一样,存于堆中开辟的.bss和.data段,是共享的
d. 文件等公用资源  这个是共享的,使用这些公共资源的线程必须同步。

2、同一进程线程的独享资源:
a. 栈 栈是独享的

3、线程的三种同步机制
互斥
读写锁
条件变量

4、参数传递和资源共享的区别

1)参数传递:main函数中的一个结构体传入新建的线程中,代码如下:

#include<stdio.h>

#include<pthread.h>
typedef struct profile
{
char *name;
int high;
}S_Profile;

void *create(void *arg)
{
S_Profile *info = (S_Profile *)arg;
printf("the thread start ....\n");
printf("the name=%s and high=%d\n", info->name, info->high);
}

int main(int argc, char *argv[])
{
pthread_t tid;
S_Profile *pt;
int err;

pt = (S_Profile *)malloc(sizeof(S_Profile));
pt->name = "cxy";
pt->high = 173;
err = pthread_create(&tid, NULL, create, (void *)pt);
if(err != 0 )
{
printf("the thread create failed!\n");
return -1;
}
sleep(1);
printf("main end...\n");
}

输出结果:

the thread start ....
the name=cxy and high=173
main end...

2)资源共享 :新建立的线程可以共享进程中的数据

#include<stdio.h>
#include<pthread.h>

int a = 3;

void * create(void *argc)
{
printf("the thread start ....\n");
printf("the a=%d\n", a);
}
int main(int argc, char *argv[])
{
pthread_t tid;
int err;
int b = 2;


err = pthread_create(&tid, NULL, create, NULL);
if(err != 0)
{
printf("create sub thread failed!\n");
return -1;
}
sleep(1);

printf("the b=%d\n", b);

printf("main end...\n");

}

输出结果:

the thread start ....
the a=3
the b=2
main end...