not working threads in sfml - c++

Hi for beginning I want to say that I'm new in this stuff so sorry for this basic question.
#include <SFML/System.hpp>
#include <iostream>
void func()
{
// this function is started when thread.launch() is called
for (int i = 0; i < 10; ++i)
std::cout << "I'm thread number one" << std::endl;
}
int main()
{
// create a thread with func() as entry point
sf::Thread thread(&func);
// run it
thread.launch();
// the main thread continues to run...
for (int i = 0; i < 10; ++i)
std::cout << "I'm the main thread" << std::endl;
return 0;
}
this is code from sfml offical site and it should be printing:
I'm thread number one
I'm the main thread
I'm the main thread
I'm thread number one
I'm thread number one
etc but console print first 10x times "I'm thread number one" and the the second one and i have no idea why. I used this tutorial to install sfml https://youtu.be/axIgxBQVBg0 .

The example from SFML's website is an example of potential output. If you notice the output given in that example seems a little unpredictable that is because it is. You are extremely unlikely to reproduce it. As noted in the comments you won't have explicit control over the threads without further synchronization.

Related

Unable to create real multithreading in C++ (using for loop)

I am new to C++ and I am trying to create multiple threads using for loop. Here is the code
#include <iostream>
#include <thread>
class Threader{
public:
int foo(int z){
std::cout << "Calling this function with value :" << z << std::endl;
return 0;
}
};
int main()
{
Threader *m;
std::cout << "Hello world!" << std::endl;
std::thread t1;
for(int i = 0; i < 5; i++){
std::thread t1(&Threader::foo, m, i);
t1.join();
}
return 0;
}
This is the output
As you can see the function I am calling is being invoked using Thread 5 times, but I have to do a t1.join inside the for loop. Without the join the for loop fails in the very first iteration. Like shown here
But if I use the join(), then the threads are being created and executed sequentially cause join() waits for each thread completion. I could easily achieve Actual multithreading in Java by creating Threads in a loop using runnable methods.
How can I create 5 threads which would run absolutely parallel in C++?

How to print to standard output from multiple threads using POCO in c++

I want to create a simple program that starts 5 threads that print "hello world! This is thread [thread number]".
Each print operation should be preceded by a random wait operation, to demonstrate that the threads are running concurrently. (The threads will print their message in a random order, as opposed to printing in order which would happen if the threads are running sequentially.)
Here is the code that should achieve this:
Poco::Thread thread[5];
class HelloRunnable: public Poco::Runnable
{
public:
HelloRunnable(int arg)
{
n = arg;
}
int n;
virtual void run()
{
usleep(rand()%100000);
std::cout << "Hello, world! This is thread " << n << std::endl;
}
};
int main()
{
for(int i=0; i<5; i++)
{
HelloRunnable runnable(i);
thread[i].start(runnable);
}
for(int i=0; i<5; i++)
{
thread[i].join();
}
return 0;
}
However, at run time, this gives the error:
//pure virtual method called
//terminate called without an active exception
//The program has unexpectedly finished.
If instead, I put thread[i].join() inside the same for loop as thread[i].start(), then the program runs without error but it prints the threads in order. (Becuase join() waits until the thread has finished before moving on, hence the threads are executed sequentially and not concurrently.
How can I make the threads run concurrently and print out the message to the standard output as soon as cout is called?
Since you create the objects inside the for loop their lifetime will end immediately after each iteration. This will cause issues. As the documentation for start() states:
Note that the given Runnable object must remain valid during the entire lifetime of the thread, as only a reference to it is stored internally.
You need to create the runnables in a way that keeps them alive outside the loop also.
As Sami has said, the runnable was destroyed before the thread had finished. I removed the for loops and typed each line out explicitly. I also removed a thread as I can only run 4 threads without causing a crash. Finally, I created a separate runnable for each thread, as in the original code each thread was using the same one.
Poco::Thread thread[5];
class HelloRunnable: public Poco::Runnable
{
public:
HelloRunnable(int arg)
{
n = arg;
}
int n;
virtual void run()
{
//sleep for random length of time
timeval t;
gettimeofday(&t, NULL);
srand(t.tv_usec * t.tv_sec);
int uS = rand()%100000;
usleep(uS);
//print message
std::cout << "Hello, world! This is thread " << n << " I slept for "<< uS << "uS" <<std::endl;
return;
}
};
int main()
{
HelloRunnable runnable1(1);
thread[1].start(runnable1);
HelloRunnable runnable2(2);
thread[2].start(runnable2);
HelloRunnable runnable3(3);
thread[3].start(runnable3);
HelloRunnable runnable4(4);
thread[4].start(runnable4);
thread[1].join();
thread[2].join();
thread[3].join();
thread[4].join();
return 0;
}

Execute callback function on main thread from std::thread

I have a requirement of executing a callback function on exit of a std::thread and the callback function should be executed on the main thread.
On thread creation I need to detach the thread and cannot block the main loop execution for thread completion.
i tried using std::signal but that does not seem to execute callback function on the main thread
#include <thread>
#include <csignal>
#include <iostream>
std::thread::id main_thread_id;
void func2()
{
for(int i = 0; i < 10000000; i++)
{
// do something
}
}
void func()
{
for(int i = 0; i < 10; i++)
{
func2();
}
std::raise(SIGUSR1);
}
void callback(int signal)
{
std::cout << "SIGNAL: " << signal << " THREAD ID:" <<
std::this_thread::get_id() << std::endl;
bool b = std::this_thread::get_id() == main_thread_id;
std::cout << "IS EXECUTED ON MAIN THREAD: " << b << std::endl;
}
int main()
{
main_thread_id = std::this_thread::get_id();
std::cout << "MAIN THREAD ID: " << std::this_thread::get_id() << std::endl;
std::signal(SIGUSR1, callback);
std::thread t1(func);
t1.detach();
for(int i = 0; i < 20; i++)
{
func2();
}
if(t1.joinable())
t1.join();
}
The result I get is that the callback function is not executed on main thread. Please suggest a way in which I can create a worker thread and call a callback function on main thread upon exit of the thread.
Thanks for the help
There are a few ways to do this.
First, your main thread could be running a message loop. In which case, you queue up a message with a payload that tells the main thread to run some code (either carry the code to run via a pointer part of the message to the main thread, or put it in some known spot that the main thread checks).
A second approach is to return something like a std::future<std::function<void()>> object, and the main thread checks if the future is ready. When it is ready, it runs the code.
A third approach is to create a concurrent queue that the main thread waits on, and stuff your message (containing code to run) onto that queue.
All of these things require the active cooperation of the main thread. The main thread cannot be preemted and told to run different code without its cooperation.
Which is best depends on features of your program you did not choose to mention in your question. If you are a graphical GUI with a message loop, use the message loop. If you are a streaming processor that paralellizes some work, and you don't need prompt execution, yet eventually will want to block on the parallel work, a future might be best. If you are a message passing channel-type app, a set of queues might be best.

Mutex & Threads: Explanation

I have been reading over the following tutorial: C++ Multithreading Tutorial.
I have compiled the code in the tutorial that creates ten unique threads and print a string with the thread number.
Here is what the code looks like for those who don't want to open the link:
#include <iostream>
#include <thread>
static const int num_threads = 10;
//This function will be called from a thread
void call_from_thread(int tid) {
std::cout << "Launched by thread " << tid << std::endl;
}
int main() {
std::thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
When I run the code it compiles and the output is kind of random.
It will launch each thread but it won't launch them in order.
I was reading the C++ reference on std::mutex and it sounds like that is what I need.
So, I was wondering if someone could give me a quick rundown over how to implement std:mutex in code like this to ensure that the threads don't use the same shared resource and to ensure that they launch in order.
The threads are created in the right order, but the order of scheduling of their execution is not guaranteed to be the same.
Is mutex the solution ?
You could attempt to add a mutex. This will only assure that two threads are not in the critical section at the same time:
std::mutex mtx;
void call_from_thread(int tid) {
std::lock_guard<std::mutex> lock(mtx); // holds the lock until scope is left
std::cout << "Launched by thread " << tid << std::endl;
}
Note tha I didn't lock the mutex directly and I prefered the lock_guard: this locks the mutex using RAII which is exception safe.
Online demo 1
Is atomic the solution
Another way to do multithreading without mutex, is to use atomic variables. These are guaranteed to be accessed by one thread at a time without data race.
std::atomic<int> cnt{0};
void call_from_thread(int tid) {
while (cnt!=tid)
std::this_thread::yield();
std::cout << "Launched by thread " << tid << std::endl;
cnt++;
}
Of course the code above is useless: it just makes sure that threads are executed in sequence. Every thread looks it the global atomic counter corresponds to its number. if yes, it executes and increments the global counter. If not, it just gives the opportunity to another thread to execute.
Online demo 2
Of course this construct here is a waste of time. Normally, you'd use condition variables to do something like this. it's only for illustration.
Conclusion
Multithreading is quite complex. If you want to dig into it, I highly recommend Anthony William's book "C++ Concurrency in action", which is an excellent step by step introduction, not only to C++ multithreading libraries, but more generally challenges of multithreaded algorithms.

Thread inside another thread in a while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm pretty new to C++ and I'm experimenting with threads right now.
I'm trying to create a thread inside a thread under a while loop. But I don't think it seems to be working.
Presently my code looks like this:
#include <>
std::vector<pthread_t> outer_thread, inner_thread;
void *inner_thread(void *ptr)
{
string data1;
data1 = *(reinterpret_cast<string*>(ptr));
cout << "inner thread started " << data1;
/* do something */
cout << "inner thread stopped " << data1;
pthread_exit(NULL);
return 0;
}
void *outer_thread(void *ptr )
{
cout << "out thread started" << endl;
//cout << ptr << endl;
//cout << *(reinterpret_cast<string*>(ptr)) << endl;
string data;
data = *(reinterpret_cast<string*>(ptr));
string str3;
while (getline(data,str3))
{
cout << "out thread started" << endl;
pthread_t in_thread;
in_vec.push_back(str3);
int create_thread2 = pthread_create(&in_thread, NULL, &inner_thread, reinterpret_cast<void*>(&(in_vec.at(j))));
inner_thread.push_back(in_thread);
if (create_thread2 != 0)
cout << "Error : Thread";
j++;
cout << "out thread ends " << j << create_thread2 << endl ;
}
for (int k = 0; k < j ; k++)
{
pthread_join(inner_thread.at(k),NULL) ;
}
pthread_exit(NULL);
return 0;
}
int main (int argc, char *argv[])
{
int i = 0;
while (getline(gin,str))
{
string str1;
pthread_t out_thread;
cout << "str1" << str1 << endl;
now_vec.push_back(str1);
int create_thread = pthread_create(&out_thread, NULL, &outer_thread, reinterpret_cast<void*>(&(now_vec.at(i))));
outer_thread.push_back(out_thread);
if (create_thread != 0) cout << "Error : Thread" ;
i++;
}
for (int k = 0 ; k < i; k ++)
{
cout << i << endl;
//cout << "third thread " << outer_thread.at(1) << endl;
cout << outer_thread.at(k) << endl;
cout << "out out out" << endl;
pthread_join(outer_thread.at(k),NULL) ;
}
}
I'm trying to read a file which contains the list of files that should be read. I want to read all these files simultaneously.
All these files contain information and needs another set of threads to start another operation. So this also needs to be done simultaneously.
That's the reason I have 2 sets of threads running.
Let me know If there is any faster and simpler way to do this?
It seems to wait till the inner thread finishes and then starts with the next iteration. I want the inner threads to run simultaneously inside the outer thread. May I know how to go about this?
Your view of the operation of threads is wrong. A thread does not operate within another thread. They are independent streams of execution within the same process and their coexistence is flat, not hierarchical.
Some simple rules to follow when working with multiple threads:
Creating threads is expensive, so avoid creating and destroying them rapidly. It is best to create your threads once at the start of your application and assign them work to do as work becomes available.
When doing computational work, avoid creating more threads than can simultaneously execute on your CPU. Any additional threads will cause excess context switches and slow down your application.
Avoid the use of shared resources as often as possible, if a data structure must be shared between threads try and find a lock free implementation. If your shared resource is not available in a lock free implementation then use locks to protect it, but be very careful, improper use of locks can result in your application deadlocked or the performance of you application degrading to the serial execution case (as if there was only one thread).
In your particular case, if you want to speed up the processing of multiple files by processing them in parallel (and assuming the only task these threads need to achieve is the processing of these files), then a possible solution would look like:
Read in the list of files to operate on
Divide the list into sections (one section for each logical processor on you CPU).
Create your worker threads (one per logical processor) passing in their section of the file list (do not try to join with the thread in the same loop that creates it, this will block until the thread has finished executing causing your application to execute serially instead of in parallel, which is the case in the sample code you provided)
The worker threads can loop over their list of files, reading them one at a time and processing them.
In contrast to you proposed solution this one will not create a thread per file. Instead it will create as many threads as can run in parallel on your CPU avoiding the excessive context switching.
A primitive example of the above:
#include <pthread.h>
#include <vector>
#include <string>
#define NUM_THREADS 4
std::vector<std::string> work_pool[NUM_THREADS];
void *worker_thread(void *args);
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
// Read list of files here, distribute them evenly amongst the work_pools
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, worker_thread, (void *)i);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
void *worker_thread(void *args)
{
const int id = (int)args;
std::vector<std::string>::iterator it;
for (it = work_pool[id].begin(); it != work_pool[id].end(); it++) {
// Read file and process it here
}
return NULL;
}
Not sure what you're trying to do, but among the many syntax errors that I hope come from simplying your code, this is what happens:
Main thread spawns a thread (1) and wait for it to finish (join)
(1) thread executes outer_thread and spawns another thread (2) and wait for it to finish (join)
(2) thread executes inner_thread and finish.
(2) gets joined and (1) thread is able to finish.
(1) gets joined and the main thread is able to go to the next iteration.
process starts again.
Note that you don't have any parallel execution, because your threads are waiting for other finish.
Note that throwing threads at a task is not the way to speed up.
Threads are a way of either:
Better using your CPU resources (when you have multiple CPU resources... and only using as many threads as CPU resources you have)
Simplifying the organization of your code by encapsulating requests as threads (but this kind of trick scale very badly)