Table of Contents

C - C++ Threads - Thread safe function

thread_safe_function.hpp

#pragma once
 
#include <string>
 
void thread_safe_function(std::string str);

thread_safe_function.cpp

#include "thread_safe_function.hpp"
#include <string>
#include <iostream>
#include <mutex>
 
std::mutex mtx;
 
void thread_safe_function(std::string str)
{
  std::lock_guard<std::mutex> lck(mtx);
 
  std::cout << str << std::endl;
}

References

https://en.cppreference.com/w/cpp/thread/lock_guard