Professional Documents
Culture Documents
Os Lab Process Management Ex. No. - 4: "Stdafx.h"
Os Lab Process Management Ex. No. - 4: "Stdafx.h"
– 4
#include "stdafx.h"
#include <Windows.h>
#include <thread>
#include <iostream>
getchar();
return 0;
}
Prog-2-
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
void task2()
{
for(int i=1; i<=20 ; i++)
cout<<" i = "<<i<<endl;
}
void task3()
{
int x,y;
cout<<"enter 2 numbers \n";
cin>>x>>y;
cout<<x*y;
thread_2.join();
thread_1.join();
thread_3.join();
/*(Joining means that the thread who invoked the new thread will wait for the new
thread to finish execution, before it will continue its own execution). */
getchar();
return 0;
}
Note: When thread::join() is called, the calling thread will block until the thread of
execution has completed. Basically, this is one mechanism that can be used to know when
a thread has finished. When thread::join() returns, the OS thread of execution has
completed and the C++ threadobject can be destroyed.
The thread::detach() is called, the thread of execution is "detached" from the thread object
and is no longer represented by a thread object - they are two independent things. The
C++ threadobject can be destroyed and the OS thread of execution can continue on. If the
program needs to know when that thread of execution has completed, some other
mechanism needs to be used. join() cannot be called on that thread object any more,
since it is no longer associated with a thread of execution.
Prog-3-
#include "stdafx.h"
// CPP program to demonstrate multithreading using three different callables.
#include <iostream>
#include <thread>
using namespace std;
void func(int a)
{
for (int i = 0; i < a; i++) {
cout << "Thread using function pointer as callable\n";
}
}
// A callable object
class thread_obj {
public:
void operator()(int x)
{
for (int i = 0; i < x; i++)
cout << "Thread using function object as callable\n";
}
};
int main()
{
cout << "Threads 1 and 2 and 3 operating independently" << endl;