Questions tagged [stdthread]
std::thread is a C++11 standard library class which represents a single thread of execution. Threads allow multiple functions to execute concurrently.
595
questions
8
votes
0
answers
85
views
How to design a base class that needs to join a thread in its destructor, which operates on the same class instance?
I just got a juicy race condition. Consider the following classes:
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
class A
{
std::thread th;
...
0
votes
4
answers
95
views
When using std::thread class, why exactly can I pass lambda expression that capture variables by reference?
I'm having a hard time with the following std::thread's note (from cppref):
The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread ...
0
votes
1
answer
76
views
Compiler error: "invoke: No matching overloaded function found" when creating a new thread
I have the following C++ code:
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <chrono>
void ThreadFunc(std::vector<int>* ...
4
votes
1
answer
80
views
Why std::thread accepts generic lambdas but not templated functions (without explicit instantiation)?
Why is it legal to pass generic lambdas to std::thread() without any specialization, while, on the other hand, this is illegal with function templates.
The following demonstrates my query.
#include &...
6
votes
2
answers
134
views
Why std::thread() passes arguments by value (and why the reason given by Dr. Stroustrup is incorrect)?
Quoting from The C++ Programming Language (by Bjarne Stroustrup), page 1213
The thread constructors are variadic templates (§28.6). This implies that to pass a reference to a
thread constructor, we ...
1
vote
2
answers
80
views
Check if an std::thread finished execution without std::thread::join()
I found this stack-overflow question about this but it is 11 years old and I was wondering if there's a better way to do this as the question was posted in C++11 times.
There is std::thread::joinable()...
1
vote
1
answer
82
views
How does the compiler know what instructions to block when jthread::join is called?
Take this code:
#include <iostream>
#include <thread>
using namespace std::literals;
void print(std::string msg) {
while (true) {
std::cout << msg << '\n';
...
10
votes
0
answers
302
views
Why isn't a thread_local variable destroyed when the thread returns?
For a better understanding of this question, here is the code:
// code 1
#include <iostream>
#include <thread>
struct tls_test {
tls_test()
{ std::cout << "tls_test ...
2
votes
2
answers
90
views
why std::thread can be returned with not copyable limitation?
I'm quite confused about the successful compilation of the code below. The variable 't' in the function 'g' is obviously a left-value. When 'g' returns to the main function, 't' should be copied. ...
16
votes
2
answers
712
views
Capturing a `thread_local` in a lambda
Capturing a thread_local in a lambda:
#include <iostream>
#include <thread>
#include <string>
struct Person
{
std::string name;
};
int main()
{
thread_local Person user{&...
1
vote
0
answers
24
views
How passing argument as const reference works? [duplicate]
I am not able to figure out why output of the code is 10.
I have created one function printA that excepts int as const reference, from main I have created one thread and called printA, thread is kept ...
1
vote
1
answer
74
views
With very short sleep times, why does a thread only finish zero or one iteration of printing before seeing the stop flag set?
See the code below, AsyncTask creates a peer thread(timer) to increment a atomic variable and sleep for a while. The expected output is to print counter_ 10 times, with values ranging from 1 to 10, ...
1
vote
2
answers
116
views
Why does this code sporadically hang on std::condition_variable::wait()?
I have implemented a quite standard single-consumer-multiple-producer pattern, in C++ with the addition that there is a limit on the number of tasks in the queue.
A Worker runs a message queue on a ...
0
votes
1
answer
104
views
Is there any case where it's valid to unlock then lock an unlocked mutex, while another thread tries to lock it with a lock_guard?
I apologize for the poor title, just looking for someone to confirm Im not crazy.
I recently stumbled across some code that has been in use for years without anyone complaining. The reason I was ...
0
votes
0
answers
51
views
Why exactly does `std::shared_ptr` get copied when passed to a `std::thread` as an argument? [duplicate]
I'd like to verify my understanding of how std::thread makes a copy of a shared_ptr when it is passed one as an argument.
Assume the following code (C++ 17):
#include <iostream>
#include <...
5
votes
2
answers
141
views
How does this simple multithread code lead to memory corruption?
The following code reliably produces a segfault.
#include <vector>
#include <thread>
class Class {
public:
Class(const int integer)
: cinteger(integer), carray(std::array<...
1
vote
1
answer
91
views
When thread's destructor is being called?
I came across an example of basic std::thread usage from "The C++ programming language" by Bjarne Stroustrup, and it confuses me. Here is the example:
void run(int i, int n) // warning: ...
1
vote
0
answers
53
views
Multithread programming [duplicate]
I am new in multithread programming in c++. Today I had read that there is no copy constructor of std::thread and std::promise, my question is stupid simple: why? Yes, I understand that in some cases ...
1
vote
1
answer
68
views
Weird thread behavior when moving the printf statement below increment/decrement on "count" variable
why does the program work when the printf after count++ or count-- is uncommented?
what i am trying to do is launch 2 threads, one will increment the shared resource by 1, and the other will decrement ...
0
votes
1
answer
463
views
Memory leak with OpenCV and std:thread
I have a rather really simple piece of code, I generate some cv::Mat images inside a function (myFunction) and fill an std::vector with them, whilst the vector is been filled the memory usage increase ...
-2
votes
1
answer
105
views
std::thread segfault with null native thread
Can you help me understand why this code is giving me a segfault as below? Could there be a problem in the way I create threads? I'm having difficulty understanding the issue. Please note that I have ...
0
votes
1
answer
71
views
vector becomes empty when the operator() is executed by std::thread
I’m trying to create a thread (PrinStringManager) which in turn creates several threads (PrintEntry) (depending on the number of elements of the incoming vector of strings).
Each PrintEntry thread ...
2
votes
1
answer
176
views
Force kill a C++ thread which is stuck on some blocking function
I have std::thread which listens for netlink events from the Linux kernel, It has an infinite while loop and a blocking function which blocks until the next event. I want to stop the thread forcefully ...
3
votes
1
answer
456
views
How should I wait for thread to finish with a timeout using C++11?
I have Windows multi-threaded code that I'm trying to make portable by using the C++11 thread and synchronization classes. How should the main thread wait for a worker thread with a timeout? I tried ...
-1
votes
3
answers
321
views
Why do I get "Segmentation fault (core dumped)" error when trying to implement multithreading in c++?
I have a main file where I plan to initiate the threads for my c++ program, for now, I only want to get one of the threads up and running before moving on to the others, but that is proving to be ...
1
vote
1
answer
104
views
How does std::thread generate concurrent processes on the OS?
I'm interested in implementing a thread class, purely as a learning exercise. What is the interface that std::thread uses to be able to run/stop concurrent processes on an OS? Is there a standard ...
-1
votes
1
answer
87
views
std::thread dosnt dosnt excute funtion c++
i have this simple function :
class Timer {
std::atomic<bool> active{true};
public:
void setInterval(auto function, int interval);
void stop();
};
void ...
4
votes
1
answer
743
views
Understanding condition_variable::wait for blocking a thread
While implementing a thread pool pattern in C++ based on this, I came across a few questions.
Let's assume minimal code sample:
std::mutex thread_mutex;
std::condition_variable thread_condition;
void ...
0
votes
3
answers
87
views
C++ multithreaded version of creating vector of random numbers slower than single-threaded version
I am trying to write a multi-threaded program to produce a vector of N*NumPerThread uniform random integers, where N is the return value of std::thread::hardware_concurrency() and NumPerThread is the ...
1
vote
2
answers
159
views
Thread pool with individual std::function jobs per worker crashes with segmentation fault
I have successfully implemented the thread pool from an answer on Stack Overflow, which helped me in speeding up my program. It uses a single std::queue to distribute jobs (std::function<void()>)...
0
votes
0
answers
77
views
gstreamer every 3 seconds using threads
I want to call these two functions using thread
void serviceAudio::readSong()
{
/* Start playing */
gst_element_set_state(pipeline, GST_STATE_PLAYING);
}
void serviceAudio::makeTime()
{
...
-1
votes
1
answer
200
views
How to wait for a thread to finish without high CPU load?
I have a program that creates multiple working threads and then wait's for them to finish.
The code is equivalent to this:
The worker functions both contain infinite loops and do not finish during ...
0
votes
0
answers
207
views
C++ std::thread inside class and std::vector
What is a proper way to add std::thread into class and vector?
I have a class that containing threads. I need to create threads and to save them in vector.
How to do it correctly?
class CIED
{
public:
...
0
votes
1
answer
105
views
How to pack std::thread with template constructor and lambda function?
Why is data in func() repeated?
#include <memory>
#include <thread>
#include <unistd.h>
#include <vector>
struct Data {
int id;
};
class Thread {
public:
...
0
votes
0
answers
53
views
Is there a way to parallelize efficiently with a shared memory?
I am running a simulation where I have to compute the energy of my system. The system primarily has two types of particles, and in my energy computation, I loop through all instances of each type of ...
1
vote
1
answer
80
views
I am not able to print the output on the screen. I am using cppreference side (GCC 12.1 (c++20 )) compiler
I am not able to print the output on the screen.I am using cppreference side (GCC 12.1 (c++20
)) compiler, Is there any deadlock situation in below example. Is there any online compiler i can use for ...
0
votes
1
answer
163
views
Problems with forwarding arguments to std::thread constructor
I am trying to create a class Thread that aims to wrap std::thread in such a way that it doesn't immmediately start upon construction, but rather has to be started separately. This requires a template ...
0
votes
2
answers
413
views
Create new instance of std::thread/std::jthread on every read call
I am developing a serial port program using boost::asio.
In synchronous mode I create a thread every time read_sync function is called. All reading related operation are carried in this thread (...
3
votes
1
answer
178
views
How to handle a PostMessageThread message in std::thread?
Somewhere in my main thread I am calling PostThreadMessage(). But I don't know how to handle it in the std::thread I have sent it to.
I am trying to handle it in std::thread like this:
while(true) {
...
0
votes
0
answers
307
views
What happens if a std::thread variable goes out of scope
Considering this piece of code:
#include <thread>
void foo()
{
std::thread mythread(
[=](int x)
{
// do some lengthy processing
// ...
}, 0);
mythread.detach();
}
...
0
votes
2
answers
95
views
Can object’s property be used, if object used in another thread?
Can the example below make undefined behavior and crash when main thread try to call SetX, because, although x property is not being accessed in new thread, but object itself is?
class Object{
public:
...
0
votes
4
answers
442
views
Destructor, when object's dynamic variable is locked by mutex will not free it?
I'm trying to solve some complicated (for me at least) asynchronous scenario at once, but I think it will be better to understand more simple case.
Consider an object, that has allocated memory, ...
0
votes
1
answer
117
views
Load bitmap asynchronously Direct2D C++
I have a class that represents an gui-element, that has method to set an image on it's background:
class Element
{
public:
ID2D1Bitmap *image;
ID2D1DeviceContext *target;
int x, y, width, height;
...
2
votes
1
answer
107
views
Is it safe to read variable modfied before thread creation concurrently?
// pseudocode for illustration
int g = 0;
void fn() {
if (g == 1) {
std::cout << "hello" << std::endl;
} else {
std::cout << "world" << std::...
0
votes
0
answers
180
views
How to correctly using mutex in OpenCV-ROS Threads?
I have just started using C++ for some image processing tasks. I want to integrate my RGB (OpenCV Mat) and Depth (PCL) data which I get from ros::Subscribe into colored-pointcloud data.
I use the cv::...
0
votes
0
answers
28
views
Can't call function from class by std::thread [duplicate]
I'm trying to make a class Threads to call for example 20 classes called Thread that will perform an action. Thread contains only function, this funtion is Compress and informations about the thread(...
0
votes
1
answer
289
views
std::thread(threadFunction, this); causes error in visual studio, but not visual studio code
So I have the following c++ class which stores a std::thread as a member variable, and starts a member function in that separate thread. However, this code only builds in visual studio code (using ...
2
votes
2
answers
366
views
How does std::thread store variadic arguments passed through its constructor?
Let's say I declare a thread with the following code:
#include <thread>
#include <iostream>
void printStuff(const char* c, long x) {
std::cout << x << " bottles of &...
1
vote
1
answer
102
views
C++ - weird thread behavior when pass vector to method
I wrote the following code and noticed a weird behavior.
#include <iostream>
#include <vector>
#include <thread>
void withVectorArg(double waitTime, std::vector<int> q = {}) {
...
0
votes
0
answers
99
views
Real world example of getting value from std::future before std::thread::join is called
I start learning about std::thread and std::future, and wrote very trivial example (I wanted to get the value from std::future before std::thread ends):
#include <iostream>
#include <future&...