When using std::this_thread::get_id() on CodeBlocks using the c++11 compiler, the thread numbers start from 2. Every time I run the code bellow it prints threads 2 - 6 instead of 0 - 4. Why?
Could it be possible that some other c++ application that is running in the background is using up thread IDs 1 and 2? What sorcery is this?
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
std::mutex m;
class TClass
{
public:
void run()
{
m.lock();
cout << "Hello, I'm thread " << std::this_thread::get_id() << endl;
m.unlock();
}
};
int main()
{
TClass tc;
std::thread t[5];
for (int i=0; i<5; i++)
{
t[i] = std::thread(&TClass::run, &tc);
}
for (int i=0; i<5; i++)
{
t[i].join();
}
cout << "All threads terminated." << endl;
}
There are no guarantee about the values returned by std::this_thread::get_id(). You cannot assume that the value will begin from zero or will be sequential. That is unspecified.
Related
I'm trying to write a program in C++ which will be responsible for simulating blinkers in cars. I want it to be simple and to compile it in a console window.
Is it possible to create one thread for input which will be always active and second for output that will run simultaneously?
I wanted to use threads to solve this but it doesn't work as I would like. I have a little trouble to understand threads. If anyone could help me to fix this I would be grateful.
int in()
{
int i;
cout<<"press 1 for left blinker or 0 to turn it off: ";
cin>>i;
return i;
}
void leftBlinker()
{
int i;
cout << "<-";
Sleep(1000/3);
cout << " ";
Sleep(1000/3);
}
int main()
{
thread t1 (in);
if (in()==1)
{
for (int i=0; i<100; i++)
{
thread t2(leftBlinker);
if (in()==0)
break;
}
}
system("pause");
return 0;
}
Here is a simple example code:
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
int in(std::atomic_int &i) {
while (true) {
std::cout << "press 1 for left blinker or 0 to turn it off: ";
int input;
std::cin >> input;
i = input;
}
}
void leftBlinker(std::atomic_int &i) {
while (true) {
if (i) {
std::cout << "<-" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds{333});
std::cout << " " << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds{333});
}
}
}
int main() {
std::atomic_int i{0};
std::thread t1(in, std::ref(i));
std::thread t2(leftBlinker, std::ref(i));
t1.join();
t2.join();
return 0;
}
A reference to std::atomic_int is passed to both functions for communication. std::atomic_int ensures thread-safe reads and writes. At the end you should join or detach the threads.
Someone can tell me what is wrong with this code?
I want to show 'a' with 200ms delay
eg. number 3 will show after 200ms
numbers 2 and 1 the same, but I can't write correct code to do this.
#include <iostream>
#include <cstdlib>
#include <string>
#include <windows.h>
using namespace std;
int main() {
int a=3;
do {
cout<<a<<endl;
a-=1;
string tekst = a;
for (int i = 0; i < tekst.length(); i++) { // Czasowe pokazanie napisu//
cout << tekst[i];
cout << tekst[i];
Sleep(200);
}
}
while (a=1);
getch();
}
I want to show 'a' with 200ms delay eg. number 3 will show after 200ms numbers 2 and 1 the same, but I can't write correct code to do this.
In that case, your Sleep is misplaced since it's placed after printing. You also do not need to convert the int to a std::string before printing it. ints are perfectly streamable out of the box.
Your do-while loop is also wrong. while (a=1); assigns the value 1 to a so the loop will go on forever since 1 will be implicitly converted to true.
A portable way to sleep 200 ms would be using the std::this_thread::sleep_for() function instead of Sleep() which is not a standard function.
It could look like this:
#include <chrono> // std::chrono::milliseconds
#include <iostream>
#include <thread> // std::this_thread::sleep_for
using namespace std::chrono_literals;
int main() {
for(int a=3; a>0; --a) {
// sleep for 200 ms, the standard way
std::this_thread::sleep_for(200ms);
std::cout << a << std::flush;
// or: std::cout << a << '\n';
}
}
Update for old versions of Dev C++ that doesn't support <thread> and <chrono>:
#include <iostream>
int main() {
for(int a=3; a>0; --a) {
Sleep(200);
std::cout << a << std::flush;
// or: std::cout << a << '\n';
}
}
Having:
class CPU() {};
void executable() {} , inside CPU; this function is executed by a thread.
void executable(){
while(run) { // for thread
cout << "Printing the memory:" << endl;
for (auto& t : map) {
cout << t.first << " " << t.second << "\n";
}
}
}
Need to instantiate 5 threads that execute executable() function:
for (int i = 0; i < 5; i++)
threads.push_back(thread(&CPU::executable, this)); //creating threads
cout << "Synchronizing all threads...\n";
for (auto& th : threads) th.join(); //waits for all of them to finish
Now, I want to create:
void executable0 () {
while(run) {
cout << "Printing the memory:" << endl;
for (auto& t : map) {
cout << t.first << " " << t.second << "\n";
}
}
}
void executable1 () {....}
to executable4() {....} // using that five threads that I`ve done above.
How could I do? Initialize or using std:thread constructor?
Can someone give me an example to understand this process.
Thanks & regards!
Following Some programmer dude's comment, I would also advise using a standard container of std::function:
#include <iostream>
#include <thread>
#include <map>
#include <functional>
#include <vector>
class CPU {
std::vector<std::function<void()>> executables{};
std::vector<std::thread> threads{};
public:
CPU() {
executables.emplace_back([](){
std::cout << "executable0\n";
});
executables.emplace_back([](){
std::cout << "executable1\n";
});
executables.emplace_back([](){
std::cout << "executable2\n";
});
}
void create_and_exec_threads() {
for(const auto executable : executables) {
threads.emplace_back([=](){ executable(); });
}
for(auto& thread : threads) {
thread.join();
}
}
};
We create a vector holding three callbacks, which will be used to initialise threads and start them inside create_and_exec_threads method.
Please do note that, as opposed to the comment in your example, creating a std::thread with a callback passed to its contructor will not only construct the thread, but also it will start it immediately.
Additionally, the std::thread::join method does not start the the thread. It waits for it to finish.
I have a class object obj1 and I am trying to call a member function sdf_write from 2-separate-threads.
There is a static variable wr_count inside the member-function.
The issue is: when I run both threads, the wr_count value is being shared between both threads.
For e.g. thread_1 runs 8-times and makes the wr_count=8 but when thread_2 starts it makes the wr_count=9. I want thread_2 to start counting from "1" not from the last value of thread_1.
Here is my code:
#include <iostream>
#include <stdio.h>
#include <thread>
#include "sdf_func.hpp"
#include <vector>
using namespace std;
int main() {
sdf obj1;
std::thread t1([&obj1](){
for (int i=0; i<30; i++) {
while (!obj1.sdf_write(10));
};
});
t1.detach();
std::thread t2([&obj1](){
for (int i=0; i<30; i++) {
while (!obj1.sdf_write(10));
};
});
t2.join();
cout << "done: " << obj1.done << endl;
// cout << "done: " << obj2.done << endl;
// cout << "wr_count: " << obj1.wr_count << endl;
return 0;
}
// This is sdf_func/////////////////
#include <iostream>
#include <stdio.h>
#include <thread>
#include <mutex>
using namespace std;
class sdf {
public:
int done;
std::mutex mutex;
sdf() : done(0){};
void increment() {
std::lock_guard<std::mutex> guard(mutex);
++done;
}
bool sdf_write (auto size) {
static int wr_count = 0;
if (wr_count == size) {
wr_count = 0;
increment();
//cout << "done : " << done;
return false;
}
wr_count++;
cout << wr_count << "--" << std::this_thread::get_id() << endl;
return true;
}
};
This is a perfect job for the thread_local storage duration, which is a keyword introduced from C++11.
thread_local int wr_count;
Essentially, you get a separate static instance of wr_count per thread; each one is initialised to 0.
Reference: http://en.cppreference.com/w/cpp/keyword/thread_local
I have a program doing 'assignments' that are scheduled by boost::threadpool. Each of those assignments take a lot of time (1 min - 5h per assignment). I wan't to monitor progress for each assignment, to understand how long will the process take.
There are a lot more assignments then there are threads, so only NUM_THREADS of progress outputs should be visible.
I have created a simple piece of code that does this, but there 2 problems:
I don't think it's elegant.
Don't know if incrementing prog like this is safe.
What would be the better ways of doing this?
#include <thread>
#include <iostream>
#include <atomic>
#include <vector>
volatile int prog[4]={0,0,0,0};
std::atomic<bool> prog_lock[4];
bool end(){
bool ret=true;
for(int i=0;i<4;i++)
if(prog[i]!=100){
ret=false;
break;
}
return ret;
}
void Func(){
int prog_ind=0;
for(int i=0;i<4;i++){
if(!prog_lock[i].exchange(true)){
prog_ind=i;
break;
}
}
for(int i=0;i<100;i++){
prog[prog_ind]++;
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
prog_lock[prog_ind].store(false);
}
int main(){
for(int i=0;i<4;i++)
prog_lock[i].store(false);
std::vector<std::thread> thr;
for(int i=0;i<4;i++){
thr.push_back(std::thread(Func));
}
while(!end()){
std::cout << std::string(50,' ') << "\r";
for(int i=0;i<4;i++){
std::cout << "Progress: " << prog[i] << "/100\t";
}
std::cout << "\r" << std::flush;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
for(int i=0;i<4;i++)
thr[i].join();
}