c++线程间通信 共享内存和消息传递

工作项目中遇到了两个线程需要通信,第一个方案是消息传递,用了ZMQ,后来ZMQ在使用中会崩溃,且找不到原因,只能舍弃,另一个方案是共享内存。这两者的区别大致为:

  • 共享内存
    通信机制:线程之间共享程序的公共状态,线程之间通过写-读内存中的公共状态来隐式进行通信。
    同步机制:同步是显式进行的。程序员必须显式指定某个方法或某段代码需要在线程之间互斥执行。
  • 消息传递:
    通信机制:线程之间没有公共状态,线程之间必须通过明确的发送消息来显式进行通信。
    同步机制:由于消息的发送必须在消息的接收之前,因此同步是隐式进行的。

共享内存的相关代码:

char share_buffer[4096]; //share_data
	strcpy(share_buffer, HardwarePlatformStat::UploadThread::GBKToUTF8(db_path_.c_str()));
	// create shared memory file
	 file_shared_handler = CreateFile(LPCTSTR(L"HardwarePlatformStat_shared_memory"), //shared_file_name,
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		OPEN_ALWAYS, // open exist or create new, overwrite file
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	
	if (file_shared_handler == INVALID_HANDLE_VALUE)
		cout << "create file error" << endl;

	 file_mapping_handler = CreateFileMapping(
		file_shared_handler, // Use paging file - shared memory
		NULL,                 // Default security attributes
		PAGE_READWRITE,       // Allow read and write access
		0,                    // High-order DWORD of file mapping max size
		buff_size,            // Low-order DWORD of file mapping max size
		LPCTSTR("HardwarePlatformStat_shared_memory"));  // Name of the file mapping object

	// map memory file view, get pointer to the shared memory
	 lp = MapViewOfFile(
		file_mapping_handler,  // Handle of the map object
		FILE_MAP_ALL_ACCESS,  // Read and write access
		0,                    // High-order DWORD of the file offset
		0,                    // Low-order DWORD of the file offset
		buff_size);           // The number of bytes to map to view

	// copy data to shared memory
	memcpy(lp, &share_buffer, sizeof(share_buffer));

	FlushViewOfFile(lp, buff_size);

做个记录防止遗忘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值