日期:2014-05-16 浏览次数:20868 次
/*********************************************************************************/
/*
进程的互斥量共享属性
默认:PTHREAD_PROCESS_PRIVATE 0
PTHREAD_PROCESS_SHARED
*/
/********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
typedef struct foo
{
int f_count;
pthread_mutex_t f_lock;
int data;
}foo;
int main()
{
pthread_mutexattr_t attr;
int pshared;
pid_t pid;
foo d;
if (pthread_mutexattr_init(&attr) != 0) //初始线程属性,这是必须的
{
printf("pthread_attr_init error!\n");
}
//设置共享属性
/**********************************这里怎么设置属性为0和1都一样啊??*******************************/
if (pthread_mutexattr_setpshared(&attr, 1) != 0)
{
printf("pthread_attr_init error!\n");
}
if (pthread_mutexattr_getpshared(&attr, &pshared) != 0)
{
printf("pthread_attr_init error!\n");
}
//printf("%d\n", pshared);
if (pthread_mutex_init(&(d.f_lock), &attr) != 0)
{
printf("pthread_mutex_init error!\n");
}
if (pthread_mutexattr_destroy(&attr) != 0) //销毁属性占的空间
{
printf("pthread_attr_init error!\n");
}
d.data = 2; //数据初始化为1
/*if (pthread_mutex_lock(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_init error!\n");
}
d.data ++;
printf("%d\n", d.data);
if (pthread_mutex_unlock(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_init error!\n");
}*/
//用两个进程来测试
if ((pid = fork()) < 0)
{
printf("fork error!\n");
}
else if (pid == 0)
{
if (pthread_mutex_unlock(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_lock error!\n");
}
printf("%d\n", d.data);
d.data = 8;
printf("%d\n", d.data);
if (pthread_mutex_unlock(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_unlock error!\n");
}
}
else
{
if (pthread_mutex_lock(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_lock error!\n");
}
printf("%d\n", d.data);
d.data = 12;
printf("%d\n", d.data);
if (pthread_mutex_unlock(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_unlock error!\n");
}
if (pthread_mutex_destroy(&(d.f_lock) ) != 0)
{
printf("pthread_mutex_destroy error!\n");
}
}
return 0;
}
划线地方怎么设置属性为0和1都一样啊?