मैं सी ++ में म्यूटेक्स के बारे में सीख रहा हूं और निम्नलिखित कोड (एन जोसुटिस 'से लिया गया है "सी ++ मानक लाइब्रेरी") में समस्या है।सी ++ प्रोग्राम अप्रत्याशित रूप से ब्लॉक/फेंकता
मुझे समझ नहीं आता क्यों यह ब्लॉक/फेंकता जब तक कि मैं मुख्य थ्रेड मेंthis_thread::sleep_for
जोड़ने (तो यह ब्लॉक नहीं करता है और सभी तीन कॉल किया जाता है)।
कंपाइलर cl.exe कमांड लाइन से उपयोग किया जाता है।
#include <future>
#include <mutex>
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
std::mutex printMutex;
void print(const std::string& s)
{
std::lock_guard<std::mutex> lg(printMutex);
for (char c : s)
{
std::cout.put(c);
}
std::cout << std::endl;
}
int main()
{
auto f1 = std::async(std::launch::async, print, "Hello from thread 1");
auto f2 = std::async(std::launch::async, print, "Hello from thread 2");
// std::this_thread::sleep_for(std::chrono::seconds(1));
print(std::string("Hello from main"));
}
आप धागे को खत्म करने की प्रतीक्षा नहीं कर रहे हैं। मुझे लगता है कि यह एमएसवीसी लाइब्रेरी के साथ यहां एक मुद्दा है। – Niall