Professional Documents
Culture Documents
CS0051 - Module 02
CS0051 - Module 02
Concurrent Programming
Module 1
Subtopic 1
Concurrency in C++
• To install appropriate IDE and build tools for C++
• To perform various ways of specifying code to run on a
new thread
• To perform simple thread management
• To implement data sharing among threads
• To determine problems associated with sharing data
between threads
https://en.cppreference.com/w/cpp/thread
#include <iostream>
#include <thread>
int main() {
}
int main()
#include <iostream>
{
#include <thread>
cout << "Hello World from main()" << endl;
using namespace std; thread t1(hellofunction);
HelloObject ho;
void hellofunction(){ thread t2(&HelloObject::objectfunction, &ho);
cout << "Hello from function..." << endl; //runs HelloObject::objectfunction() on object ho
}
t1.join();
class HelloObject {
public:
t2.join();
void objectfunction();
};
}
void HelloObject::objectfunction(){
cout << "Hello from object function" <<endl;
}
• When a thread object goes out of scope and it is in
joinable state, the program is terminated.
• join() - waits for the thread to finish its execution
HelloObject ho;
thread t2(&HelloObject::objectfunction, &ho); //runs HelloObject::objectfunction() on object
ho
t1.join()
t2.join()
}
int main()
{
cout << "Hello World from main()" << endl;
thread t1(hellofunction);
HelloObject ho;
thread t2(&HelloObject::objectfunction, &ho); //runs HelloObject::objectfunction() on object ho
t1.detach();
t2.detach();
}
#include <iostream>
#include <thread>
int main()
{
using namespace std; HelloObject ho;
thread t1(ho);
t1.join();
class HelloObject {
public: cout << "\nmain() program ends..." << endl;
void operator()(){
}
cout << "Hello object method thread..." << endl;
}
};
#include <iostream> int main()
#include <thread> {
#include <string>
cout << "Hello World from main()" << endl;
using namespace std; thread t1(hellofunction,5, "FEUTECH");
HelloObject ho;
void hellofunction(int n, string str){ thread t2(&HelloObject::objectfunction, &ho, 5, "FEUTECH");
t1.join();
for(int i=0; i<n; i++)
t2.join();
cout << "Hello from function... " << " " << str << endl;
}
cout << "\nmain() program ends..." << endl;
class HelloObject {
public:
void objectfunction(int n, string str); }
};
class HelloObject {
public:
void objectfunction(int n, string str);
};