本文整理汇总了C++中Mutex类的典型用法代码示例。如果您正苦于以下问题:C++ Mutex类的具体用法?C++ Mutex怎么用?C++ Mutex使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Mutex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: unlockMutex
void BadaMutexManager::unlockMutex(OSystem::MutexRef mutex) {
Mutex *m = (Mutex*)mutex;
m->Release();
}
示例2: lockMutex
void BadaMutexManager::lockMutex(OSystem::MutexRef mutex) {
Mutex *m = (Mutex*)mutex;
m->Acquire();
}
示例3: wait
void ThreadCondition::wait(Mutex& mutex)
{
m_condition.timedWait(mutex.impl(), INFINITE);
}
示例4: wait
bool Condition::wait(Mutex& mutex)
{
return SDL_CondWait(p.get(), mutex.raw_ptr()) == 0;
}
示例5: v3f
void ClientLauncher::speed_tests()
{
// volatile to avoid some potential compiler optimisations
volatile static s16 temp16;
volatile static f32 tempf;
static v3f tempv3f1;
static v3f tempv3f2;
static std::string tempstring;
static std::string tempstring2;
tempv3f1 = v3f();
tempv3f2 = v3f();
tempstring = std::string();
tempstring2 = std::string();
{
infostream << "The following test should take around 20ms." << std::endl;
TimeTaker timer("Testing std::string speed");
const u32 jj = 10000;
for (u32 j = 0; j < jj; j++) {
tempstring = "";
tempstring2 = "";
const u32 ii = 10;
for (u32 i = 0; i < ii; i++) {
tempstring2 += "asd";
}
for (u32 i = 0; i < ii+1; i++) {
tempstring += "asd";
if (tempstring == tempstring2)
break;
}
}
}
infostream << "All of the following tests should take around 100ms each."
<< std::endl;
{
TimeTaker timer("Testing floating-point conversion speed");
tempf = 0.001;
for (u32 i = 0; i < 4000000; i++) {
temp16 += tempf;
tempf += 0.001;
}
}
{
TimeTaker timer("Testing floating-point vector speed");
tempv3f1 = v3f(1, 2, 3);
tempv3f2 = v3f(4, 5, 6);
for (u32 i = 0; i < 10000000; i++) {
tempf += tempv3f1.dotProduct(tempv3f2);
tempv3f2 += v3f(7, 8, 9);
}
}
{
TimeTaker timer("Testing std::map speed");
std::map<v2s16, f32> map1;
tempf = -324;
const s16 ii = 300;
for (s16 y = 0; y < ii; y++) {
for (s16 x = 0; x < ii; x++) {
map1[v2s16(x, y)] = tempf;
tempf += 1;
}
}
for (s16 y = ii - 1; y >= 0; y--) {
for (s16 x = 0; x < ii; x++) {
tempf = map1[v2s16(x, y)];
}
}
}
{
infostream << "Around 5000/ms should do well here." << std::endl;
TimeTaker timer("Testing mutex speed");
Mutex m;
u32 n = 0;
u32 i = 0;
do {
n += 10000;
for (; i < n; i++) {
m.lock();
m.unlock();
}
}
// Do at least 10ms
while(timer.getTimerTime() < 10);
u32 dtime = timer.stop();
u32 per_ms = n / dtime;
infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
}
}
示例6: Rehash
bool Rehash()
{
#ifdef WIN32
char * config_file = "ascent-logonserver.conf";
#else
char * config_file = (char*)CONFDIR "/ascent-logonserver.conf";
#endif
if(!Config.MainConfig.SetSource(config_file))
{
printf("Config file could not be rehashed.\n");
return false;
}
m_encryptedPasswords = Config.MainConfig.GetBoolDefault("LogonServer", "UseEncryptedPasswords", false);
// re-set the allowed server IP's
string ips = Config.MainConfig.GetStringDefault("LogonServer", "AllowedIPs", "");
string ipsmod = Config.MainConfig.GetStringDefault("LogonServer", "AllowedModIPs", "");
vector<string> vips = StrSplit(ips, " ");
vector<string> vipsmod = StrSplit(ips, " ");
m_allowedIpLock.Acquire();
m_allowedIps.clear();
m_allowedModIps.clear();
vector<string>::iterator itr;
for(itr = vips.begin(); itr != vips.end(); ++itr)
{
string::size_type i = itr->find("/");
if( i == string::npos )
{
printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
continue;
}
string stmp = itr->substr(0, i);
string smask = itr->substr(i+1);
unsigned int ipraw = MakeIP(stmp.c_str());
unsigned int ipmask = atoi(smask.c_str());
if( ipraw == 0 || ipmask == 0 )
{
printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
continue;
}
AllowedIP tmp;
tmp.Bytes = ipmask;
tmp.IP = ipraw;
m_allowedIps.push_back(tmp);
}
for(itr = vipsmod.begin(); itr != vipsmod.end(); ++itr)
{
string::size_type i = itr->find("/");
if( i == string::npos )
{
printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
continue;
}
string stmp = itr->substr(0, i);
string smask = itr->substr(i+1);
unsigned int ipraw = MakeIP(stmp.c_str());
unsigned int ipmask = atoi(smask.c_str());
if( ipraw == 0 || ipmask == 0 )
{
printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
continue;
}
AllowedIP tmp;
tmp.Bytes = ipmask;
tmp.IP = ipraw;
m_allowedModIps.push_back(tmp);
}
if( InformationCore::getSingletonPtr() != NULL )
sInfoCore.CheckServers();
m_allowedIpLock.Release();
return true;
}
示例7: main
int main(int argc, char **argv)
{
std::string LocSocket = "/tmp/ipdupdetect";
std::unique_ptr<PIDFile> PidFile;
std::string LocPidFile = "";
const char *opts = "hdp:";
int longindex = 0;
int c = 0;
int debug = 0;
struct option loptions[]
{
{"help", 0, 0, 'h'},
{"pid", 1, 0, 'p'},
{"debug", 0, 0, 'd'},
{0, 0, 0, 0}
};
while( (c = getopt_long(argc, argv, opts, loptions, &longindex)) >= 0)
{
switch(c)
{
case 'd':
debug = 1;
break;
case 'h':
print_help(stdout, argv[0]);
exit(EXIT_SUCCESS);
break;
case 'p':
LocPidFile = optarg;
break;
default:
break;
}
}
//Add Logging
if (isatty(fileno(stdout)) == 1)
{
std::shared_ptr<ILogger> tmp = std::make_shared<LogStdoutColor>();
LogManager::Add(tmp);
} else {
std::shared_ptr<ILogger> tmp = std::make_shared<LogStdout>();
LogManager::Add(tmp);
}
if (debug)
{
LogManager::SetLevel(LOGGER_DEBUG);
}
else
{
LogManager::SetLevel(LOGGER_INFO);
}
if (LocPidFile != "")
{
PidFile.reset(new PIDFile(LocPidFile));
if (PidFile->Create() == false)
{
LogCritical("Cannot Create PID file '%s'", LocPidFile.c_str());
exit(EXIT_FAILURE);
}
LogInfo("Created PID file '%s'", LocPidFile.c_str());
}
SigHandler SHandler;
SignalHandler Signals = SignalHandler(&SHandler);
Signals.Block();
do
{
ServerManager *SrvManager = NULL;
MonitorManager MManager;
Service *Srv = new Service(&MManager); //Bind instance of MonitorManager to the ServiceProxy
struct timespec timeout = {60, 0}; //Timeout to reprocess interface list
ScopedLock lock(&ExitLock);
SHandler.SetMonitorManager(&MManager); //Bind MonitorManager to signal handler proxy
ServerUnixPolled Unix(LocSocket); //Create a suitable socket
SrvManager = new ServerManager(Srv); //Create a new server instance
SrvManager->ServerAdd(&Unix); //Bind our Service proxy to the socket instance
Signals.UnBlock();
while(DoExit == false)
{
MManager.Scan();
MManager.Purge();
ExitLock.Wait(&timeout);
}
lock.Unlock(); //Required to prevent hang in signals
SrvManager->ServerRemove(&Unix);
delete Srv;
delete SrvManager;
Signals.Block();
SHandler.SetMonitorManager(NULL);
Signals.UnBlock();
//.........这里部分代码省略.........
示例8: assert
bool
KRT2Device::DataReceived(const void *_data, size_t length,
struct NMEAInfo &info)
{
assert(_data != nullptr);
assert(length > 0);
const uint8_t *data = (const uint8_t *)_data;
const uint8_t *end = data + length;
do {
// Append new data to the buffer, as much as fits in there
auto range = rx_buf.Write();
if (rx_buf.IsFull()) {
// Overflow: reset buffer to recover quickly
rx_buf.Clear();
expected_msg_length = 0;
continue;
}
size_t nbytes = std::min(range.size, size_t(end - data));
memcpy(range.data, data, nbytes);
data += nbytes;
rx_buf.Append(nbytes);
for (;;) {
// Read data from buffer to handle the messages
range = rx_buf.Read();
if (range.IsEmpty())
break;
if (range.size < expected_msg_length)
break;
expected_msg_length = ExpectedMsgLength(range.data, range.size);
if (range.size >= expected_msg_length) {
switch (*(const uint8_t *) range.data) {
case ACK:
case NAK:
// Received a response to a normal command (STX)
response_mutex.Lock();
response = *(const uint8_t *) range.data;
// Signal the response to the TX thread
rx_cond.signal();
response_mutex.Unlock();
break;
default:
// Received a command from the radio -> ignore it
break;
}
// Message handled -> remove message
rx_buf.Consume(expected_msg_length);
expected_msg_length = 0;
// Received something from the radio -> the connection is alive
info.alive.Update(info.clock);
}
}
} while (data < end);
return true;
}
示例9: main
int main(int argc, char* argv[])
{
Component a, b, c;
// Force components to use JTCP...
//a.AddService(new JTCPClient());
//b.AddService(new JTCPClient());
//c.AddService(new JTCPClient());
// Try load settings files.
// These files determine your UDP network
// settings, what Services to turn on/off
// or any Service specific settings. See the
// example file for settings file format.
if(a.LoadSettings("settings/services.xml") == false ||
b.LoadSettings("settings/services.xml") == false ||
c.LoadSettings("settings/services.xml") == false)
{
// Working directory probably not set (or not running from output directory), so
// use default values.
a.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
"Simulation");
b.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
"Simulation");
c.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
"Simulation");
}
// Use a callback to know when heartbeat messages were receive
CallbackTest callback;
a.TransportService()->RegisterCallback(EVENT, &callback);
// Initialize a component with any ID.
std::cout << "Initializing Component A...";
if(a.Initialize(Address(60001, 1, 1)) == false)
{
std::cout << "Failed to Initialize Component A.\n";
return 0;
}
std::cout << "Success!\n";
std::cout << "Initializing Component B...";
// Initialize a component with a given ID.
if(b.Initialize(Address(60002, 1, 1)) == false)
{
std::cout << "Failed to Initialize Component B.\n";
return 0;
}
std::cout << "Success!\n";
std::cout << "Initializing Component C...";
// Initialize a component with a given ID.
if(c.Initialize(Address(60003, 1, 1)) == false)
{
std::cout << "Failed to Initialize Component C.\n";
return 0;
}
std::cout << "Success!\n";
// Enable Debug Messages for testing.
//a.TransportService()->EnableDebugMessages(true);
//b.TransportService()->EnableDebugMessages(true);
//a.LivenessService()->EnableDebugMessages(true);
//a.EventsService()->EnableDebugMessages(true);
//b.EventsService()->EnableDebugMessages(true);
//a.TransportService()->EnableLogging(true);
// Allow time for connections to establish before trying
// to send a query.
CxUtils::SleepMs(1000);
// Example inline message query - Get subsystem ID of component B
QueryIdentification queryIdent(b.GetComponentID(), a.GetComponentID());
queryIdent.SetQueryType(QueryIdentification::SubsystemIdentification);
ReportIdentification reportIdent;
if(a.Send(&queryIdent, &reportIdent, 1000))
{
reportIdent.Print();
}
Time::Stamp startTimeMs = Time::GetUtcTimeMs();
while(CxUtils::GetChar() != 27)
{
static bool createdEvent = false;
if(!createdEvent && !a.EventsService()->HaveSubscription(REPORT_HEARTBEAT_PULSE, b.GetComponentID()))
{
// Request Heartbeat Events from component b.
QueryHeartbeatPulse query;
createdEvent = a.EventsService()->RequestPeriodicEvent(b.GetComponentID(),
&query,
10,
1);
}
gPrintLock.Lock();
//a.DiscoveryService()->PrintSystemConfiguration();
//b.DiscoveryService()->PrintSystemConfiguration();
c.DiscoveryService()->PrintSystemConfiguration();
//.........这里部分代码省略.........
示例12: gSetLogFile
void gSetLogFile(FILE *wFile)
{
gLogLock.lock();
gLoggingFile = wFile;
gLogLock.unlock();
}
示例13: popAllCommands
void DroneController::popAllCommands()
{
m_mutex.lock();
while(!m_commandStack.empty()) m_commandStack.pop();
m_mutex.unlock();
}
示例14: popCommand
void DroneController::popCommand()
{
m_mutex.lock();
if(!m_commandStack.empty()) m_commandStack.pop();
m_mutex.unlock();
}
示例15: clearPosition
void DroneController::clearPosition()
{
m_mutex.lock();
m_velIntegrator.clear();
m_mutex.unlock();
}