工作项目中遇到了两个线程需要通信,第一个方案是消息传递,用了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);
做个记录防止遗忘