CxUtils使用
本文转自:http://blog.sina.com.cn/s/blog_6e0693f70100sawf.html
CxUtils是一款包含了很多实用函数的跨平台C++函数库。这个库里面支持包装了多线程操作,网络通讯,游戏摇杆编程,串口通信,共享内存操作,定时器,键盘和鼠标捕获,以及基本的数学运算。这个函数库可以跨平台应用在windows,linux,或其它操作系统上。本文主要介绍了CxUtils的安装方法,及其使用CxUtils创建共享内用于多线程通讯的例子。
test
#include "stdafx.h"
#include <iostream>
#include <vector>
#include "cxutils/ipc/mappedmemory.h"
#include "cxutils/thread.h"
#include "cxutils/keyboard.h"
using namespace std;
using namespace CxUtils;
// Number of threads writing to shared memory.
const int NUM_THREADS = 10;
void WriteToMemory(void *arg);
class ThreadData
{
public:
ThreadData()
{
mPos = 0;
}
~ThreadData() {}
string mName;
unsigned int mPos;
static bool mLoop;
};
bool ThreadData::mLoop = true;
int main(int argc, char **argv)
{
char name[128] = "Mem_Example";
Thread threads[NUM_THREADS];
MappedMemory mem;
ThreadData data[NUM_THREADS];
cout << "Creating Shared Memory...";
if(!mem.CreateMappedMemory(name, NUM_THREADS*sizeof(unsigned short)))
{
cout << "Could not create shared/mapped memory: " << name << endl;
return 0;
}
cout << "Success\n";
// If no additional program arguments passed, create threads
// that will write to shared memory. You can also use the
// cxipc_client.cpp program to write to shared memory also.
if(argc == 1)
{
for(int i = 0; i < NUM_THREADS; i++)
{
// Set encode position for the thread to use.
data[i].mPos = i*sizeof(unsigned short);
data[i].mName = name;
// Create thread.
threads[i].CreateThread(WriteToMemory, (void *)(&data[i]));
}
}
while(true)
{
if(GetChar() == 27)
{
for(int i = 0; i < NUM_THREADS; i++)
{
data[i].mLoop = false;
}
break;
}
unsigned short count = 0;
mem->SetReadPos(0);
mem.Lock(); // Must lock for read/write safety.
for(int i = 0; i < NUM_THREADS; i++)
{
count = 0;
mem->Read(count);
cout << count << " ";
}
mem.Unlock(); // Must unlock to prevent deadlock.
cout << "\n";
SleepMs(1);
}
for(int i = 0; i < NUM_THREADS; i++)
{
data[i].mLoop = false;
SleepMs(1);
threads[i].StopThread();
}
return 0;
}
void WriteToMemory(void *arg)
{
string name;
unsigned int epos = 0;
unsigned short count = 0;
MappedMemory mem;
ThreadData *info = (ThreadData *)(arg);
if(!arg)
return;
name = info->mName; // Name of memory.
epos = info->mPos; // Write position.
SleepMs(50);
if(mem.OpenMappedMemory(name.c_str()) == 0)
{
cout << "Could not open shared/mapped memory: " << name << endl;
return;
}
while(info->mLoop)
{
mem.Lock();
mem->Write(++count, epos);
mem.Unlock();
SleepMs(1);
}
}