本文整理汇总了C++中std::mutex类的典型用法代码示例。如果您正苦于以下问题:C++ mutex类的具体用法?C++ mutex怎么用?C++ mutex使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了mutex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: primitive
std::mutex::native_handle_type primitive()
{ return m.native_handle(); }
示例2: networkThread
// Worker thread
static void networkThread(void)
{
HttpRequest *request = NULL;
while (true)
{
if (s_need_quit)
{
break;
}
// step 1: send http request if the requestQueue isn't empty
request = NULL;
s_requestQueueMutex.lock();
//Get request task from queue
if (0 != s_requestQueue->count())
{
request = dynamic_cast<HttpRequest*>(s_requestQueue->objectAtIndex(0));
s_requestQueue->removeObjectAtIndex(0);
}
s_requestQueueMutex.unlock();
if (NULL == request)
{
// Wait for http request tasks from main thread
std::unique_lock<std::mutex> lk(s_SleepMutex);
s_SleepCondition.wait(lk);
continue;
}
// step 2: libcurl sync access
// Create a HttpResponse object, the default setting is http access failed
HttpResponse *response = new HttpResponse(request);
// request's refcount = 2 here, it's retained by HttpRespose constructor
request->release();
// ok, refcount = 1 now, only HttpResponse hold it.
int32_t responseCode = -1;
int retValue = 0;
// Process the request -> get response packet
switch (request->getRequestType())
{
case HttpRequest::kHttpGet: // HTTP GET
retValue = processGetTask(request,
writeData,
response->getResponseData(),
&responseCode,
writeHeaderData,
response->getResponseHeader());
break;
case HttpRequest::kHttpPost: // HTTP POST
retValue = processPostTask(request,
writeData,
response->getResponseData(),
&responseCode,
writeHeaderData,
response->getResponseHeader());
break;
case HttpRequest::kHttpPut:
retValue = processPutTask(request,
writeData,
response->getResponseData(),
&responseCode,
writeHeaderData,
response->getResponseHeader());
break;
case HttpRequest::kHttpDelete:
retValue = processDeleteTask(request,
writeData,
response->getResponseData(),
&responseCode,
writeHeaderData,
response->getResponseHeader());
break;
default:
CCASSERT(true, "CCHttpClient: unkown request type, only GET and POSt are supported");
break;
}
// write data to HttpResponse
response->setResponseCode(responseCode);
if (retValue != 0)
{
response->setSucceed(false);
response->setErrorBuffer(s_errorBuffer);
}
else
//.........这里部分代码省略.........
示例3: now
namespace clog {
std::mutex m;
struct logger2 {
std::stringstream ss;
const char *level;
std::string now()
{
time_t t = time(NULL);
struct tm *tm_info;
tm_info = localtime(&t);
char buf[20];
strftime(buf, 20, "%F %T", tm_info);
return std::string(buf);
}
logger2(const char *llevel)
{
level = llevel;
}
void flush(std::ostream &out)
{
m.lock();
out << level << ": " << now() << " "
<< ss.str() << std::endl;
m.unlock();
}
virtual ~logger2()
{
}
template <typename t>
logger2& operator<<(const t s)
{
ss << s;
return *this;
}
};
/* TODO Copy and pasted code. */
struct err : public logger2 {
#ifdef CPP_LOG_ERR_FILE
std::ofstream ofs;
#endif
err() : logger2("Error") {
#ifdef CPP_LOG_ERR_FILE
ofs.open(CPP_LOG_ERR_FILE,
std::ios_base::app | std::ios_base::out);
#endif
};
~err() {
#ifdef CPP_LOG_ERR_COUT
flush(std::cout);
#endif
#ifdef CPP_LOG_ERR_CERR
flush(std::cerr);
#endif
#ifdef CPP_LOG_ERR_FILE
flush(ofs);
ofs.close();
#endif
}
};
struct warn : public logger2 {
#ifdef CPP_LOG_WARN_FILE
std::ofstream ofs;
#endif
warn() : logger2("Warning") {
#ifdef CPP_LOG_WARN_FILE
ofs.open(CPP_LOG_WARN_FILE,
std::ios_base::app | std::ios_base::out);
#endif
};
~warn() {
#ifdef CPP_LOG_WARN_COUT
flush(std::cout);
#endif
#ifdef CPP_LOG_WARN_CERR
flush(std::cerr);
#endif
#ifdef CPP_LOG_WARN_FILE
flush(ofs);
ofs.close();
//.........这里部分代码省略.........
示例4: withLock
void withLock(std::mutex & m, Function f) {
m.lock();
f();
m.unlock();
}
示例5: increment
void increment(){
mutex.lock();
counter.increment();
mutex.unlock();
}
示例6: add_inj
void add_inj(int other) {
mutex.lock();
inj.push_back(other);
mutex.unlock();
}
示例7: alignas
namespace bch {
class alignas(4) Test
{
public:
Test()
{
#if BCH_SMART_PTR_UNITTEST
std::cout << "Test ctor(1)" << std::endl;
#endif
Fill(1);
}
explicit Test(int v)
{
#if BCH_SMART_PTR_UNITTEST
std::cout << "Test ctor(2)" << std::endl;
#endif
Fill(v);
}
~Test()
{
#if BCH_SMART_PTR_UNITTEST
std::cout << "Test dtor" << std::endl;
#endif
}
void Baz()
{
}
private:
void Fill(int v)
{
for (int i = 0; i < sizeof(mValue)/sizeof(*mValue); ++i)
mValue[i] = v++;
}
char mValue[4];
};
class TestDer: public Test
{
public:
TestDer()
{
#if BCH_SMART_PTR_UNITTEST
std::cout << "TestDer ctor" << std::endl;
#endif
}
~TestDer()
{
#if BCH_SMART_PTR_UNITTEST
std::cout << "TestDer dtor" << std::endl;
#endif
}
};
template <typename T>
void Foo(T value)
{
value->Baz();
}
const unsigned int kTestCount = 100000000;
// const unsigned int kTestCount = 1;
std::mutex mutex;
double stdPtrTime = 0;
double noThreadTime = 0;
void std_poiner()
{
typedef std::chrono::time_point<std::chrono::system_clock> TimerType;
TimerType start = std::chrono::system_clock::now();
std::shared_ptr<Test> stdValue(new Test);
for (unsigned int i = 0; i < kTestCount; ++i)
{
Foo(stdValue);
}
TimerType end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
double elapsed = elapsed_seconds.count();;
{
mutex.lock();
stdPtrTime += elapsed;
std::cout << "Time with std::shared_ptr is " << elapsed << std::endl;
mutex.unlock();
}
}
void nothread_poiner()
{
typedef std::chrono::time_point<std::chrono::system_clock> TimerType;
TimerType start = std::chrono::system_clock::now();
shared_ptr_nc<Test> stdValue(new Test);
for (unsigned int i = 0; i < kTestCount; ++i)
//.........这里部分代码省略.........
示例8: func
void func(int i) {
mutex.lock();
std::cout << "func clled, i = " << i << " /" << std::this_thread::get_id() << std::endl;
mutex.unlock();
}
示例9: network
void network()
{
ENetAddress address;
ENetHost* client;
ENetPeer* peer;
std::string message;
ENetEvent event;
int eventStatus;
if (enet_initialize () != 0)
{
std::cout << "Could not start ENet." << std::endl;
return;
}else
std::cout << "Started ENet." << std::endl;
atexit(enet_deinitialize);
client = enet_host_create(NULL, 1, 2, 57600 / 8, 14400 / 8);
enet_address_set_host(&address, "localhost");
char hej[10];
enet_address_get_host(&address, hej, 10);
std::cout << hej << std::endl;
address.port = 1234;
peer = enet_host_connect(client, &address, 2, 0);
while(true)
{
while (enet_host_service(client, &event, 1000) > 0)
{
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:
std::cout << "We got a new connection " << event.peer->address.host << std::endl;
break;
case ENET_EVENT_TYPE_RECEIVE:
{
std::cout << "Message from servv: ";
//enet_peer_disconnect(peer, 3);
char header[] = {((char*) event.packet->data)[0],
((char*) event.packet->data)[1],
((char*) event.packet->data)[2],
((char*) event.packet->data)[3]};
int* headerInt = (int*) header;
std::cout << *headerInt << std::endl;
if (*headerInt == PLAYER_POSITION)
{
Package<PLAYER_POSITION_TYPE>* message = (Package<PLAYER_POSITION_TYPE>*) event.packet->data;
std::cout << "player: " << message->_player << std::endl;
std::cout << "x: " << message->_data.x << std::endl;
std::cout << "y: " << message->_data.y << std::endl;
std::cout << "z: " << message->_data.z << std::endl;
}else if (*headerInt == ASSIGN_PLAYER_NUMBER)
{
Package<int>* message = (Package<int>*) event.packet->data;
std::cout << "Player number: " << message->_data << std::endl;
}
// int message = ((char*) event.packet->data)
enet_packet_destroy(event.packet);
break;
}
case ENET_EVENT_TYPE_DISCONNECT:
std::cout << "Disconnected from serv: " << event.peer->data << std::endl;
event.peer->data = NULL;
break;
}
}
posMutex.lock();
glm::vec3 hej = pos;
posMutex.unlock();
// std::cout << "Position sent: (" << hej.x << ", " << hej.y << ", " << hej.x << ")" << std::endl;
ENetPacket* packet = enet_packet_create(&hej, sizeof(glm::vec3), ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
std::cout << "ping: " << peer->roundTripTime << " ms" << std::endl;
offMutex.lock();
if (turnOfNetwork)
{
offMutex.unlock();
std::cout << "Network recived shoudown command." << std::endl;
break;
}else
offMutex.unlock();
}
std::cout << "Turning of network." << std::endl;
enet_host_destroy(client);
}
示例11: main
int main(){
Uavcam *camera;
bool camera_ok, frame_ok;
int n_saved;
std::stringstream filename;
std::stringstream directory;
std::vector<int> jpg_params;
cv::Mat frame, preview;
parseConfig();
jpg_params.push_back(CV_IMWRITE_JPEG_QUALITY);
jpg_params.push_back(90);
//Set Signals
std::signal(SIGINT,exit_signal); //Set up Ctrl+C signal
//Construct Cameras
if (cameratype == 1){
#ifdef USE_ARAVIS
camera = new AravisCam();
std::cout<<"Using Aravis camera"<<std::endl;
#else
camera = new WebCam();
#endif
}
if(view)
cv::namedWindow("Camera Viewer", cv::WINDOW_AUTOSIZE);
n_saved = checkLog(); //Check the log and open it
openLogtoWrite(n_saved);
ublox = new Gps(); //Initialize the GPS
std::thread gps_thread(gpsUpdate);
camera_ok = camera->initializeCam(); //Initialize the camera
if (camera_ok) {
std::cout << "Start camera acquisition in " << start_delay << " seconds" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(start_delay));
while(!finish){ //--Main Acquisition Loop
filename.str(""); directory.str(""); //Update filenames
filename<<"im"<<std::setfill('0')<<std::setw(4)<<++n_saved<<".jpg";
directory<<FOLDER<<filename.str();
camera->trigger(); //Send camera trigger
if (usegps){
if(ublox->data_is_good)
std::cout<<"GPS up to date"<<std::endl;
else
std::cout<<"No GPS available" <<std::endl;
}
mtx.lock();
writeImageInfo(ublox->current_loc, filename.str()); //Record GPS
mtx.unlock();
frame_ok = camera->getImage(frame); //Acquire the image
if(frame_ok){ //Acquired Image
cv::resize(frame,preview,cv::Size(),sizefac,sizefac,cv::INTER_NEAREST);
if(saveimg) {
cv::imwrite(directory.str(), preview, jpg_params);
std::cout<<"Saved to " << filename.str() <<std::endl;
}
if(view) {
cv::imshow("Camera Viewer", preview);
cv::waitKey(50);
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
//Finished photographing
delete camera;
}
gps_thread.join();
closeLog();
return 0;
}
示例12: main
int main(int argc, const char* argv[])
{
#ifdef _WIN32
//Start up Winsock…
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
if (error) //Did something happen?
{
std::cerr<<"Unable to start winsock"<<std::endl;
return -1;
}
if (wsadata.wVersion != 0x0202)//Did we get the right Winsock version?
{
Die("version mismatch");
}
#endif
std::cout << "Enter Server URL: ";
char url[0x100];
std::cin.getline(url,sizeof(url));
std::cout << "Enter your Nickname: ";
char nickname[0x100] = ":";
std::cin.getline(nickname+1,sizeof(nickname)-1);
char*colon = strchr(url,':');
std::string surl,sport;
if (colon != NULL)
{
*colon = 0;
sport = colon+1;
}
else
{
sport = ToString(DEFAULT_PORT);
}
surl = url;
PrintLine("Attempting to connect to "+surl);
ADDRINFOA hints;
memset(&hints,0,sizeof(hints));
hints.ai_protocol = IPPROTO_TCP;
hints.ai_family = AF_UNSPEC;
//hints.
ADDRINFOA*result;
if (getaddrinfo(surl.c_str(),sport.c_str(),&hints,&result) != 0)
{
Die("Call to getaddrinfo() failed");
}
bool connected = false;
while (result) //search through all available results until one allows connection.
//Chances are we get IPv4 and IPv6 results here but the server will only answer to one of those
{
sock = socket(result->ai_family,result->ai_socktype,result->ai_protocol);
if (sock != INVALID_SOCKET) //if we can create a socket then we can attempt a connection. It would be rather unusual for this not to work but...
{
if (!connect(sock,result->ai_addr,result->ai_addrlen)) //attempt connnection
{
//connected
PrintLine("Connected to "+ToString(*result)); //yay, it worked
connected = true;
break;
}
else
{
closesocket(sock); //these aren't the droids we're looking for.
sock = INVALID_SOCKET;
}
}
result = result->ai_next; //moving on.
}
if (!connected)
Die("Failed to connect to "+surl+":"+sport); //so, yeah, none of them worked.
Submit(nickname); //includes leading ':', so that the server knows this is a name, not a message
netThread = std::thread(NetLoop); //start read-thread
while (sock != INVALID_SOCKET)
{
char c = _getch(); //keep reading characters
{
if (c == 3) //this only works on windows, but ctrl-c is handled better on linux anyway
{
Die("Ctrl+C");
break;
}
consoleLock.lock();
if (c == '\n' || c == '\r') //user pressed enter/return:
{
std::string submit = inputBuffer; //copy buffer to string
std::cout << '\r'; //move cursor to line beginning
//.........这里部分代码省略.........
示例13: globalRelease
void gl::globalRelease(bool finish) {
if (finish) {
glFinish();
}
_globalOpenGLLock.unlock();
}
示例14: log
static void log(const std::stringstream &message) {
m.lock();
std::cout << message.str() << std::endl << std::flush;
m.unlock();
}
示例15: addCommands
void CommandReceiver::addCommands(const vector<Command>& commands) {
m_stackLock.lock();
m_commandStack.insert(m_commandStack.end(), commands.begin(), commands.end());
m_stackLock.unlock();
}