Hello I am new to multithreading in C++. I am using a thread class available in C++11 in order to run a function in a different thread but somehow the output I am getting from the function is very awkward. This might be because different threads might be trying to execute the same variable at the same time and thus causing conflicts. Please suggest how should I modify my code so that I can get correct output. I am posting a sample code of what I am trying to do. This is not the original code but it just shows the flow of my original code since my original code is too long to be posted, But the problem remains same for both the cases.
#include<iostream>
#include<thread>
using namespace std;
typedef struct {
int thread_id;
char *message;
}threadData;
int display(threadData *tData){
threadData *my_data;
my_data = (threadData *) tData;
cout << "Thread ID: " << my_data -> thread_id << endl;
cout << "Message: " << my_data -> message << endl;
return 0;
}
int main(){
threadData *data;
data = (threadData *)malloc(sizeof(threadData));
data->thread_id = 12;
data->message = "This is the message";
for (int i = 0; i<10; i++)
{
std::thread t1(display, data);
t1.detach();
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire