622 questions
-2
votes
1
answer
131
views
Assign thread object after the join function in C++
As per my understanding it is fine to assign the thread object and call join function in C++ 11.
eg as below :
#include <iostream>
#include <thread>
using namespace std;
void func()
{
...
9
votes
1
answer
834
views
pointer-to-member syntax difference in g++ 13 (Linux) vs. g++ 14 (Windows)
I experienced an interesting behavior of g++ in versions 13 and 14. The following code works fine in g++14 (MSYS2, MinGW, Windows):
#include <iostream>
#include <thread>
class A
{
public:
...
1
vote
3
answers
189
views
Parallelized ray tracer is slower than single thread version
i'm writing a raytracer based on the popular raytracing in a weekend series.
i've tried to parallelize it by dividing the image in slices and give each thread a portion of the image to render:
void ...
4
votes
2
answers
149
views
Wrap std::thread in lambda with perfect forwarding
I need to wrap std::thread to do some processing (inside the new thread) before the user function runs.
At the moment I'm achieving this via a helper function, but that's a bit annoying.
How can I ...
1
vote
1
answer
52
views
std::ofstream assignment operator -- segfault only occurs in gdb
I am writing a multithreaded program in which each thread opens its own text file for primitive debug logging. Each thread is represented by a separate instance of a class, which manages both the std::...
2
votes
1
answer
110
views
Using external stop control in std::jthread to avoid duplication
Unlike std::thread, the jthread logically holds an internal private member of type std::stop_source, which maintains a shared stop-state.
(cppreference link)
I want to use an external std::...
0
votes
0
answers
23
views
Creating and linking thread getting error "std::Invoke, No matching overloaded function found" [duplicate]
// The function that the background thread will run
void runPingThread(std::promise<int>& promiseObj) {
while (!stopFlag) {
ping(); // Call the ping ...
1
vote
3
answers
224
views
Attempting to Reference Deleted Constructor with std::thread and std::vector?
I'm attempting to use a C++ class (with constructors & destructors), that has an std::thread field, in an std::vector object. I'm using C++ 17 and Visual Studio 2022 to compile all examples shown ...
0
votes
0
answers
53
views
C++ initialization of a thread in a constructor [duplicate]
Given this code in C++:
#include <vector>
#include <thread>
class MyClass {
std::thread workerThread;
std::vector<int> vec;
public:
MyClass():
workerThread(&...
0
votes
1
answer
186
views
QProcess and std::thread - Cannot create children for a parent that is in a different thread
I am getting a run-time message
QObject: Cannot create children for a parent that is in a different thread.
when starting a QProcess in a std::thread. The program runs, but I feel that this message ...
0
votes
1
answer
182
views
Virtual memory size increases considerably with thread count
In the below C++ code example, each time the user presses the Enter key, a new thread will be created. The thread waits for 10 minutes and then exits. The thread has a std::string object with some ...
1
vote
1
answer
104
views
C++ Concurrency - memory_order_acquire [duplicate]
#include <atomic>
#include <thread>
std::vector<int> queue_data;
std::atomic<int> count;
void populate_queue()
{
unsigned const number_of_items=20;
queue_data.clear();
...
2
votes
2
answers
191
views
How to spawn a single thread with OpenMP (like a std::thread()) and use "#pragma omp single" and "#pragma omp for" afterwards?
I would simply like to spawn a background thread, like std::thread, but just with OpenMP.
Is this possible?
If yes, how ist it done?
To better explain what I want to achieve, here the C++ Code of what ...
3
votes
1
answer
144
views
Why should I not pass a lambda with by-reference captures to the std::thread constructor?
I wrote a timer class, but it does not work the way I needed it to. Can anyone tell me what is wrong with this?
template<typename D, typename C>
class timer
{
public:
timer(D period, C&&...
6
votes
1
answer
2k
views
Not able to stop jthread using stop_token
very new to posting here, so apologies if it's in the wrong place.
I'm a hobby coder, so my experience is limited and while I learned C++ some years ago, I have to re-learn it periodically. Now is ...
0
votes
1
answer
90
views
recv doesn't work in a thread - Windows c++
I'm currently developing a TCP server and I use multi threading, so for this I init a server using a Server.start() which give me a fd like and then I init an infinite loop to accept and start new ...
4
votes
3
answers
250
views
What happens with a thread's arguments if thread creation fails?
Imagine I create a thread like this:
jthread thr( []( string &&str ) {}, move( str ) );
What happens if the thread creation fails ? Is the string guaranteed to keep its old contents ?
0
votes
1
answer
66
views
c++ thread: wrap thread function in lambda
#include <iostream>
#include <thread>
class MyClass {
public:
MyClass(int val) : val_(val) {}
int val_{0};
};
void threadFunction(MyClass myObj) {
// do ...
0
votes
1
answer
86
views
c++ thread function accepting object by value: why does std::ref(obj) compile?
#include <iostream>
#include <thread>
template<int Num>
class MyClass {
public:
MyClass(int val) : val_(val) {}
// Copy constructor
MyClass(const MyClass& other) : ...
1
vote
0
answers
498
views
Problem with g++ on Mac using std::thread and exceptions
this is my first question here, so feel free to ask for further information if needed.
EDIT: After the bot encouraged me to clarify my problem and state what I'd like to do: I would like to use C++ 20 ...
0
votes
0
answers
110
views
C++ lambda used in std::thread crash
This my code:
std::thread t([](){
int ret = func();
if (ret != 0){
return false;
}
});
t.detach();
As this code, compiler deduce the lambda return value type is bool, so when ret==0, the ...
0
votes
1
answer
138
views
What is wrong with this C++ multi-threaded program?
I write a multi-threaded C++ program using std::thread that looks like the following:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using ...
1
vote
0
answers
63
views
How can I run a detached thread that is waiting for a conditional variable in a loop?
I've got a very time critical simulator that is supposed to run as fast as humanly possible. I tried to increase the data throughput by distributing every data frame to multiple worker threads. To ...
0
votes
0
answers
50
views
Write-read conflicts in Linux C++ IO concurrency
Considering the writing of an online evaluation system, each JudgeTask has an independent input file path, output file path, expected file path, pending program path, and corresponding evaluation ...
1
vote
2
answers
205
views
Check if a function argument value is thread-local
In C++, is it possible to check (preferably at compile time) if a function argument reference value is thread-local?
E.g.
void foo( int& bar ) { ... }
I'd like to check/enforce that bar refer to ...
0
votes
0
answers
66
views
Constness ignored when forwarding std::reference_wrapper to lambda argument
For the following simple class:
#include <iostream>
#include <string>
#include <thread>
#include <cstring>
struct Foo_t {
int size;
char *ptr;
Foo_t(int s = 0):...
6
votes
1
answer
690
views
Does condition variable notify_one keep trying until it reaches thread awaiting with a positive predicate?
I'm testing edge cases with std::condition_variable and I tested scenario to starve one thread.
Scenario is that there are 99 producers and only one consumer, all of them working on 1 queue with max ...
8
votes
0
answers
124
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
2k
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 ...
1
vote
1
answer
211
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
110
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 &...
7
votes
2
answers
371
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
725
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
132
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
1
answer
399
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
106
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
2k
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
27
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
121
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
195
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
759
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
71
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
191
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
117
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
56
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
75
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
2k
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
225
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
104
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 ...
3
votes
1
answer
763
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 ...