本文整理汇总了C++中std::mutex::lock方法的典型用法代码示例。如果您正苦于以下问题:C++ mutex::lock方法的具体用法?C++ mutex::lock怎么用?C++ mutex::lock使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类std::mutex
的用法示例。
在下文中一共展示了mutex::lock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: withLock
void withLock(std::mutex & m, Function f) {
m.lock();
f();
m.unlock();
}
示例2: lockStatistics
void lockStatistics()
{
gTatisticsCppMutex.lock();
}
示例3: lock
void lock()
{
check_for_hierarchy_violation();
internal_mutex.lock();
update_hierarchy_value();
}
示例4: Int_UpdateThread
// Internal thread for updating the console.
void lConsole::Int_UpdateThread()
{
static std::chrono::milliseconds UpdateDelay(500);
while (true)
{
// Delay so we don't waste time updating.
std::this_thread::sleep_for(UpdateDelay);
// If we have a stream handle.
if (StreamHandle == nullptr || !ShouldPrintScrollback)
continue;
// Clear the console.
#ifdef _WIN32
// Aparently system("cls") is bad practice as it spawns a shell.
COORD topLeft = { 0, 0 };
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(
console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
FillConsoleOutputAttribute(
console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
SetConsoleCursorPosition(console, topLeft);
#else
// But nix can use ANSI escapecodes.
// CSI[2J to clear the console.
// CSI[H to reset the cursor.
fprintf(stdout, "\x1B[2J\x1B[H");
#endif
// Save the old color settings.
static CONSOLE_SCREEN_BUFFER_INFO OldTextColor;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &OldTextColor);
// For each line in the scrollback.
ThreadSafe.lock();
for (uint32_t i = 0; i < ScrollbackLineCount; ++i)
{
// Set the output strings color.
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CompatibleRGBA(ScrollbackLines[i].RGBA));
// Search the string for progress bars.
for (uint32_t c = 0; c < ProgressbarCount; ++c)
{
if (strstr(ScrollbackLines[i].String, Progressbars[c].ProgressToken))
{
static char ProgressBuffer[257];
memset(ProgressBuffer, 0, 257);
// Create the buffer.
for (int32_t k = 0; k < (int32_t)min(INT32_MAX, strlen(ScrollbackLines[i].String)) - 1; ++k)
{
// Copy all the characters up until the token.
if (ScrollbackLines[i].String[k + 0] == Progressbars[c].ProgressToken[0] &&
ScrollbackLines[i].String[k + 1] == Progressbars[c].ProgressToken[1])
{
ProgressBuffer[k] = ScrollbackLines[i].String[k];
}
else
{
// Copy the progress bar into the buffer.
// TODO: Use the bar type.
strcpy(&ProgressBuffer[c], GetProgress(0, Progressbars[c].CurrentValue, Progressbars[c].EndValue));
break;
}
}
// Print the formated buffer.
printf(ProgressBuffer);
printf("\n");
goto LABEL_PRINT_DONE;
}
}
// Print the string since there's no progress bar.
printf(ScrollbackLines[i].String);
printf("\n");
LABEL_PRINT_DONE:;
}
// Reset the color.
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), OldTextColor.wAttributes);
ThreadSafe.unlock();
}
}
示例5: updateBuffer
void QueryWorld::updateBuffer() {
m_copyWorldLock.lock();
m_queryWorld = m_copyWorld;
m_copyWorldLock.unlock();
}
示例6: DumpPacket
void DumpPacket(DWORD packetType, DWORD connectionId, DWORD opcode, BYTE opcodeSize, DWORD size, BYTE* buffer)
{
mtx.lock();
// gets the time
time_t rawTime;
time(&rawTime);
DWORD tickCount = GetTickCount();
if (!fileDump)
{
tm* date = localtime(&rawTime);
// basic file name format:
char fileName[MAX_PATH];
// removes the DLL name from the path
PathRemoveFileSpec(dllPath);
// fills the basic file name format
_snprintf(fileName, MAX_PATH,
"wowsniff_%s_%u_%u_%d-%02d-%02d_%02d-%02d-%02d.pkt",
hookInfo.locale, wowInfo.expansion, wowInfo.build,
date->tm_year + 1900,
date->tm_mon + 1,
date->tm_mday,
date->tm_hour,
date->tm_min,
date->tm_sec);
// some info
printf("Sniff dump: %s\n\n", fileName);
char fullFileName[MAX_PATH];
_snprintf(fullFileName, MAX_PATH, "%s\\%s", dllPath, fileName);
fileDump = fopen(fullFileName, "wb");
// PKT 3.1 header
fwrite("PKT", 3, 1, fileDump); // magic
fwrite((WORD*)&pkt_version, 2, 1, fileDump); // major.minor version
fwrite((BYTE*)&sniffer_id, 1, 1, fileDump); // sniffer id
fwrite((WORD*)&wowInfo.build, 2, 1, fileDump); // client build
fwrite(sessionKey, 1, 2, fileDump); // client build (aligned bytes)
fwrite(hookInfo.locale, 4, 1, fileDump); // client lang
fwrite(sessionKey, 40, 1, fileDump); // session key
fwrite((DWORD*)&rawTime, 4, 1, fileDump); // started time
fwrite((DWORD*)&tickCount, 4, 1, fileDump); // started tick's
fwrite((DWORD*)&optionalHeaderLength, 4, 1, fileDump); // opional header length
fflush(fileDump);
}
fwrite((DWORD*)&packetType, 4, 1, fileDump); // direction of the packet
fwrite((DWORD*)&connectionId, 4, 1, fileDump); // connection id
fwrite((DWORD*)&tickCount, 4, 1, fileDump); // timestamp of the packet
fwrite((DWORD*)&optionalHeaderLength, 4, 1, fileDump); // optional data size
fwrite((DWORD*)&size, 4, 1, fileDump); // size of the packet + opcode lenght
fwrite((DWORD*)&opcode, 4, 1, fileDump); // opcode
fwrite(buffer + opcodeSize, size - opcodeSize, 1, fileDump); // data
#if _DEBUG
printf("%s Opcode: 0x%04X Size: %-8u\n", packetType == CMSG ? "CMSG" : "SMSG", opcode, size);
#endif
fflush(fileDump);
mtx.unlock();
}
示例7: ChangeOutputstream
// Console modification.
void lConsole::ChangeOutputstream(void *NewStream)
{
ThreadSafe.lock();
this->StreamHandle = NewStream;
ThreadSafe.unlock();
}
示例8: imageRequset
// 멀티스레드를 위한 imageRequset
void imageRequset(string tempuri, int index)
{
int resp_leng;
string request, response;
char buffer[BUFFERSIZE];
struct sockaddr_in serveraddr;
int sock = 0;
WSADATA wsaData;
vector<char> image;
Uri *uri = new Uri;
Uri resultURL = uri->Parse(tempuri);
resultURL.Parse(tempuri);
if (resultURL.getProtocol() == "http" || resultURL.getProtocol() == "")
{
hostent* hostname = gethostbyname(resultURL.getHost().c_str());
// Init WinSock
WSADATA wsa_Data;
int wsa_ReturnCode = WSAStartup(0x101, &wsa_Data);
// Get the local hostname
struct hostent *host_entry;
host_entry = gethostbyname(resultURL.getHost().c_str());
char * ipaddress;
ipaddress = inet_ntoa(*(struct in_addr *)*host_entry->h_addr_list);
WSACleanup();
int port = 0;
if (resultURL.getPort() == "")
{
port = 80;
}
else
{
port = atoi(resultURL.getPort().c_str());
}
string path = resultURL.getPath();
if (resultURL.getHost() == "sang12456.cafe24.com")
request = "GET " + path + " HTTP/1.1\r\n\r\n";
else
request = "GET " + path + " HTTP/1.1\nHost: " + resultURL.getHost() + "\r\n\r\n";//"\nConnection : keep - alive\nCache - Control : max - age = 0\nAccept : text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, */*;q=0.8\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36\nAccept-Encoding: gzip, deflate, sdch\nAccept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4\r\n\r\n";
//init winsock
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
return;
//open socket
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return;
//connect
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(ipaddress);
serveraddr.sin_port = htons(port);
if (connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
return;
//send request
if (send(sock, request.c_str(), request.length(), 0) != request.length())
return;
//get response
//cout << "response" << endl;
response = "";
resp_leng = BUFFERSIZE;
do
{
resp_leng = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
copy(buffer, buffer + resp_leng, back_inserter(image));
} while (resp_leng != 0);
//disconnect
closesocket(sock);
//cleanup
WSACleanup();
}
else
response = "not valid";
if (image[9] == '2' && image[10] == '0' && image[11] == '0')
{
int imageLen = image.size();
char *binary = new char[imageLen];
memset(binary, 0, imageLen);
int j = 0;
for (unsigned int k = 0; k < image.size(); k++)
{
binary[j] = image[k];
j++;
}
// 임계영역
mtx.lock();
char *temp;
if ((temp = strstr(binary, "\n\n")) != NULL)
{
//.........这里部分代码省略.........
示例9: main
//.........这里部分代码省略.........
#ifdef _WIN32
//To make blocking:
unsigned long off = 0;
if (ioctlsocket(fd, FIONBIO, &off) != 0)
{
/* Handle failure. */
}
#else
fcntl(fd, F_SETFL, 0);
#endif
/* clear the set */
FD_ZERO(&set);
/* add our file descriptor to the set */
FD_SET(fd, &set);
/* Defines ACK thread */
std::thread ack_thread(waitForACK);
/* Creates a device shape */
DeviceShape ds(9, 9, 9);
ds.on(4, 4, 4);
/* Turns on one LED */
for (int i = 0; i < 9 ; i++) {
ds.on(i,i,8-i);
ds.on(i,i,i);
ds.on(i,8-i,i);
ds.on(8-i, i, i);
}
/* Creates a Request */
Request myRequest(1, 92, SET_LEDSTATS);
/* Encodes data into the buffers created by the Request */
uint8_t *ledBuffer = new uint8_t [ds.getSizeInBytes()];
ds.toArray(ledBuffer);
myRequest.encode(ledBuffer);
/* Prints the message */
#if DEBUG
std::cout << "My Request : " << myRequest.toStringDebug() << "\n";
#endif
// uint8_t* reqLinear = new uint8_t[SIZE_REQUEST];
// reqLinear={0};
// /* Resets the connection */
// RequestMessage resetConnection(1, RESET);
// resetConnection.encodeCrc();
// resetConnection.getListBuffer()[0].toArray(reqLinear);
// #if DEBUG
// std::cout << "Reset Connection : " << resetConnection.toStringDebug() << "\n";
// #endif
/* Sents it over USB */
// write(fd, reqLinear, SIZE_REQUEST);
// message_lock.lock();
// message_queue.push(buffLinear);
// message_lock.unlock();
uint8_t* buffLinear = new uint8_t[SIZE_BUFFER]();
/* Sends the Request */
for (int i = 0; i<myRequest.NbBuffers(); i++) {
/* Prints */
#if DEBUG
std::cout << "My Request buffer " << i << " : "
<< myRequest.getListBuffer()[i].toStringDebug(i) << "\n";
#endif
/* Sends it over USB */
myRequest.getListBuffer()[i].toArray(buffLinear);
#if DEBUG
printBuffer("BUFFER ", buffLinear, SIZE_BUFFER);
#endif
/* Send it over USB */
if (write(fd, buffLinear, SIZE_BUFFER) == -1)
std::cout << "error while sending buffer number " << i << " over USB \n";
message_lock.lock();
message_queue.push(buffLinear);
message_lock.unlock();
}
std::cout << "[TEST PASSED]\n";
ack_thread.detach();
close(fd);
delete [] buffLinear;
// delete [] reqLinear;
delete [] ledBuffer;
return 0;
}
示例10: callback
int callback(CSocket::connection &conn, char *recvbytes, size_t size, CServerSocket &sock)
{
//std::this_thread::sleep_for(std::chrono::seconds(1));
static const char okSignal[] = { "OK Signal" };
std::stringstream ss0;
ss0.write(okSignal, sizeof(okSignal));
conn.send(ss0);
std::stringstream ss/*(std::ios::binary | std::ios::in | std::ios::out)*/;
conn.receive(ss, 0x7FFFF);
dataStruct::dataStructT data2;
cereal::PortableBinaryInputArchive input(ss);
input(data2);
std::time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string str = std::string(ctime(&tt));
str.pop_back();
std::replace(str.begin(), str.end(), ':', '_');
std::fstream file(str + ".txt", std::ios::out | std::ios::in | std::ios::binary | std::ios::trunc);
//std::cout << "Arquivo => " << str + ".txt" << std::endl;
cereal::JSONOutputArchive out(file);
out(cereal::make_nvp("PC", data2));
conn.send(ss0);
auto removeduplicates = [](std::deque<std::string> &deq)
{
//std::cout << deq.size() << std::endl;
/*std::sort(deq.begin(), deq.end());
deq.erase(std::unique(deq.begin(), deq.end()), deq.end());*/
std::set<std::string> s;
unsigned size = deq.size();
for (unsigned i = 0; i < size; ++i) s.insert(deq[i]);
deq.assign(s.begin(), s.end());
//std::cout << deq.size() << std::endl;
};
std::deque<std::string> sendToUser;
for (auto &i : data2) {
for (auto &asd : i.second) {
if (asd.first.find("Hardware IDs") != std::string::npos)
{
svdrvsmutex.lock();
auto list = dvrs->getDriverPath(asd.second);
svdrvsmutex.unlock();
if (list.size() == 0)
continue;
removeduplicates(list);
sendToUser.insert(sendToUser.end(), list.begin(), list.end());
break;
}
}
}
auto sendFolder = [&](const std::string &path) {
HANDLE hFind;
WIN32_FIND_DATA data;
auto pos = path.find_last_of('/');
std::string folder = (pos != std::string::npos)? std::string(&(path.c_str()[++pos])) : std::to_string(rand());
if (folder.size() == 0) {
folder = std::to_string(rand());
}
sendFoldersAndFiles f(1, folder);
std::stringstream fstr(std::ios::binary | std::ios::in | std::ios::out);
cereal::PortableBinaryOutputArchive output(fstr);
output(f);
hFind = FindFirstFile((path + "/*").c_str(), &data);
if (hFind != INVALID_HANDLE_VALUE)
{
do
//.........这里部分代码省略.........
示例11: WndProc
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
int len = 0;
hwndMain = hWnd;
HBITMAP hBMP, hOldBmp;
HPALETTE hPalette, hOldPalette;
HDC hMemDC;
BITMAP bm;
HFONT font, oldfont;
RECT rect;
int width;
int height;
if (GetWindowRect(hWnd, &rect))
{
rect.left = 10;
rect.top = 45;
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
rt = rect;
rect.top += 20;
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
switch (iMessage)
{
case WM_CREATE:
// edit control
hEdit = CreateWindow("edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER |
ES_AUTOHSCROLL, 250, 10, 300, 25, hWnd, (HMENU)NULL, g_hInst, NULL);
origLVEditWndProc = (WNDPROC)SetWindowLong(hEdit, GWL_WNDPROC, (DWORD)LVEditWndProc);
case WM_KEYDOWN:
{
switch (wParam)
{
case VK_PRIOR:
scroll += 50;
InvalidateRect(hwndMain, &rt, TRUE);
break;
case VK_NEXT:
scroll -= 50;
InvalidateRect(hwndMain, &rt, TRUE);
break;
}
}
case WM_PAINT:
{
int imageCount = 0;
hdc = BeginPaint(hWnd, &ps);
//FillRect(hdc, &rt, (HBRUSH)GetStockObject(WHITE_BRUSH));
rect.top += scroll;
// dll에서 InvalidateRect를 통해서 WM_PAINT 메시지를 보낸다.
// 이때 찾은 Path는 path.txt 파일에 기록되고 이를 읽어 Window에 보여준다.
if (curState == FILESTATE)
{
// 임계영역
mtx1.lock();
ret.clear();
string line;
ifstream myfile("path.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
ret.push_back(line);
}
myfile.close();
}
mtx1.unlock();
}
// bmp local image load with double buffering
if (LoadBitmapFromBMPFile("nexon.bmp", &hBMP, &hPalette, 0))
{
GetObject(hBMP, sizeof(BITMAP), &bm);
hMemDC = CreateCompatibleDC(hdc);
hOldBmp = (HBITMAP)SelectObject(hMemDC, hBMP);
hOldPalette = SelectPalette(hdc, hPalette, FALSE);
RealizePalette(hdc);
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight,
hMemDC, 0, 0, SRCCOPY);
SelectObject(hMemDC, hOldBmp);
DeleteObject(hBMP);
SelectPalette(hdc, hOldPalette, FALSE);
DeleteObject(hPalette);
}
Graphics graphics(hdc);
Graphics memGraphics(hMemDC);
for (unsigned int i = 0; i < ret.size(); i++)
//.........这里部分代码省略.........
示例12: client_func
bool client_func(const mg_connection& connection,enum mg_event event)
{
if(event==MG_AUTH)
return true;
if(event!=MG_REQUEST)
return false;
std::string method=connection.request_method;
std::string request=connection.uri;
std::string json_set_prefix="/json_set/";
std::string json_get_prefix="/json_get";
std::cout<<"Request: "<<request<<std::endl;
try
{
if(msl::starts_with(request,json_set_prefix))
{
std::cout<<" Set JSON "+method+" Request."<<std::endl;
std::string json_set_str=request.substr(json_set_prefix.size(),request.size()-json_set_prefix.size());
if(method=="POST")
json_set_str=std::string(connection.content,connection.content_len);
std::cout<<json_set_str<<std::endl;
msl::json json=msl::deserialize(json_set_str);
std::cout<<" Parsing JSON Object:"<<std::endl;
for(auto ii:json.getMemberNames())
{
switch(json[ii].type())
{
case Json::arrayValue:
std::cout<<" Adding \""<<ii<<"\" as array."<<std::endl;
break;
case Json::objectValue:
std::cout<<" Adding \""<<ii<<"\" as object."<<std::endl;
break;
case Json::nullValue:
std::cout<<" Adding \""<<ii<<"\" as null."<<std::endl;
break;
case Json::intValue:
std::cout<<" Adding \""<<ii<<"\" as int."<<std::endl;
break;
case Json::uintValue:
std::cout<<" Adding \""<<ii<<"\" as uint."<<std::endl;
break;
case Json::realValue:
std::cout<<" Adding \""<<ii<<"\" as real."<<std::endl;
break;
case Json::stringValue:
std::cout<<" Adding \""<<ii<<"\" as string."<<std::endl;
break;
case Json::booleanValue:
std::cout<<" Adding \""<<ii<<"\" as bool."<<std::endl;
break;
default:
std::cout<<" Skipping \""<<ii<<"\" with invalid type."<<std::endl;
continue;
break;
}
database_lock.lock();
database[ii]=json[ii];
database_lock.unlock();
}
msl::client_reply(connection,"","text/plain");
return true;
}
else if(msl::starts_with(request,json_get_prefix))
{
std::cout<<" Get JSON "+method+" Request."<<std::endl;
std::string json_get_str=request.substr(json_get_prefix.size(),request.size()-json_get_prefix.size());
if(method=="POST")
json_get_str=std::string(connection.content,connection.content_len);
std::vector<std::string> paths=get_paths(json_get_str);
std::cout<<json_get_str<<std::endl;
std::cout<<" Parsing JSON Path:"<<std::endl;
database_lock.lock();
auto json_get_object=database;
database_lock.unlock();
for(auto path:paths)
{
json_get_object=json_get_object[path];
switch(json_get_object.type())
{
case Json::arrayValue:
std::cout<<" Getting \""<<path<<"\" as array."<<std::endl;
//.........这里部分代码省略.........
示例13: set
void set(T _newvalue) {
//mutex lock - not read and write at the same time
mtx.lock();
value = _newvalue;
mtx.unlock();
}
示例14: Stop
void STimer::Stop()
{
_mutex.lock();
_stop = true;
_mutex.unlock();
}
示例15: clear
void MemoryPool::clear() {
locker_.lock();
for (auto &item : pool_) { delete[] reinterpret_cast<byte_type *>(item.second); }
locker_.unlock();
}