基于互斥锁同步机制的Linux共享内存简单实例

Linux共享内存是Linux系统中进程间通信的一种方式,但是没有相应的同步机制,本文通过进程间的互斥锁实现一种简单的共享内存实例,仅供入门学习。

sm_common.h:
#ifndef __SM_COMMON_H__
#define __SM_COMMON_H__

#include <pthread.h>

#define SM_BUF_SIZE 1024
#define SM_ID 0x1122

struct sm_msg
{
	int flag;
	pthread_mutex_t sm_mutex;
	char buf[SM_BUF_SIZE];
};


#endif
</span>
<span style="font-size:18px;">sm_server.c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <pthread.h></span>

<span style="font-size:18px;">#include "sm_common.h"


int main(void)
{
	int shm_id = -1;
	int ret = -1;
	int key = -1;
	int running = 1;
	struct sm_msg *msg = NULL;
	void *shared_memory = NULL;
	pthread_mutexattr_t attr;

	pthread_mutexattr_init(&attr);
	pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
	//key = ftok( "./sm_common.h", 1 );
	//printf("key: %d\n", key);
	shm_id = shmget((key_t)SM_ID, sizeof(struct sm_msg), 0666|IPC_CREAT);
	if(shm_id < 0)
	{
	perror("fail to shmget");
	exit(1);
	}
#if 1	
	shared_memory = shmat(shm_id, NULL, 0);
	if (shared_memory == NULL) {
		perror("Failed to shmat");
		exit(1);</span>
<span style="font-size:18px;">	}

	msg = (struct sm_msg *)shared_memory;
	msg->flag = 0;
	pthread_mutex_init(&msg->sm_mutex, &attr);

	while (running) {
		pthread_mutex_lock(&msg->sm_mutex);
		if (msg->flag == 1) {
			printf("Read message: %s\n", msg->buf);
			msg->flag = 0;
			pthread_mutex_unlock(&msg->sm_mutex);
			if (strncmp(msg->buf, "exit", 4) == 0) {
				running = 0;
			}
		} else {
			printf("No available data to read, sleep...\n");
			pthread_mutex_unlock(&msg->sm_mutex);
			sleep(2);
		}</span>
<span style="font-size:18px;">	}

	ret = shmdt(shared_memory);
	if (ret < 0) {
		perror("Failed to shmdt");
		exit(1);
	}

	if(shmctl(shm_id, IPC_RMID, 0) < 0)
	{
		perror("failed to shmctl");
		exit(1);
	}
#endif
	return 0;
}
</span>


<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:18px;">sm_client.c:</span></span>
<span style="font-size:18px;">#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <pthread.h>

#include "sm_common.h"


int main(void)
{
	int shm_id = -1;
	int ret = -1;
	int key = -1;
	int running = 1;
	struct sm_msg *msg = NULL;
	void *shared_memory = NULL;
	//	key = ftok( "./sm_common.h", 1 );
	//printf("key: %d\n", key);
	shm_id = shmget((key_t)SM_ID, sizeof(struct sm_msg), 0666|IPC_CREAT);
	if(shm_id < 0)
	{
	perror("fail to shmget");
	exit(1);
	}

	shared_memory = shmat(shm_id, NULL, 0);
	if (shared_memory == NULL) {
		perror("Failed to shmat");
		exit(1);
	}

	msg = (struct sm_msg *)shared_memory;

	char buf[32];
	while (running) {
		printf("wait lock\n");
		pthread_mutex_lock(&msg->sm_mutex);
		printf("get lock\n");
		if(msg->flag == 1) {
			printf("Wait for other process's reading\n");
			pthread_mutex_unlock(&msg->sm_mutex);
			sleep(2);
		} else {
			printf("Please input data\n");
			fgets(buf, 32, stdin);
			printf("Write msg: %s\n", buf);
			strncpy(msg->buf, buf, sizeof(buf));		
			msg->flag = 1;
			if (strncmp(msg->buf, "exit", 4) == 0) {
				running = 0;
			}
			pthread_mutex_unlock(&msg->sm_mutex);
		}
	}

	ret = shmdt(shared_memory);
	if (ret < 0) {
		perror("Failed to shmdt");
		exit(1);
	}
	
#if 0 //Do thsi in server.
	if(shmctl(shm_id, IPC_RMID, 0) < 0)
	{
		perror("failed to shmctl");
		exit(1);
	}
#endif
	return 0;
}
</span>


 

<span style="font-size:18px;">Makefile:
all:
gcc -o sm_server sm_server.c -lpthread
gcc -o sm_client sm_client.c -lpthread</span>

使用方法:

1. 打开终端1,运行服务端:./sm_server

2.打开终端2,运行客户端:./sm_client

3.在终端2输入字符串,在终端1可看到相应输出

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
在多线程编程中,为了防止多个线程同时访问共享资源而导致的数据竞争问题,需要使用同步机制来实现线程间的协调和互斥。而互斥量是一种常用的同步机制,在多线程编程中被广泛使用。 互斥量是一种线程同步原语,用于保护共享资源。当一个线程需要访问共享资源时,它需要先获取该资源的互斥量。如果该互斥量已经被其他线程占用,则当前线程会被阻塞,直到该互斥量被释放。一旦该互斥量被释放,当前线程就可以获取该互斥量,访问共享资源,并将该互斥量加锁。当该线程完成对共享资源的访问后,它需要将该互斥量解锁,以便其他线程可以获取该互斥量继续访问共享资源。 互斥量的使用一般涉及到以下四个函数: 1. pthread_mutex_init():初始化互斥量; 2. pthread_mutex_lock():加锁互斥量; 3. pthread_mutex_unlock():解锁互斥量; 4. pthread_mutex_destroy():销毁互斥量。 下面是一个简单的例子,展示了如何使用互斥量实现线程同步: ``` #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; // 定义互斥量 void *thread_func(void *arg) { pthread_mutex_lock(&mutex); // 加锁互斥量 printf("Thread %ld is running.\n", pthread_self()); pthread_mutex_unlock(&mutex); // 解锁互斥量 pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t t1, t2; pthread_mutex_init(&mutex, NULL); // 初始化互斥量 pthread_create(&t1, NULL, thread_func, NULL); pthread_create(&t2, NULL, thread_func, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_mutex_destroy(&mutex); // 销毁互斥量 return 0; } ``` 在上面的例子中,我们定义了一个互斥量 mutex,然后在线程函数中分别加锁和解锁该互斥量。在主函数中,我们创建了两个线程,并等待它们执行完毕后退出程序。需要注意的是,我们必须在程序退出之前销毁该互斥量,以免产生内存泄漏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪游东戴河

你就是这个世界的唯一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值