Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added some important algorithms #97

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions C++/multithreaded_algo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// C++ program to demonstrate
// multithreading using three
// different callables.
#include <iostream>
#include <thread>
using namespace std;

// A dummy function
void foo(int Z)
{
for (int i = 0; i < Z; 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";
}
};

// class definition
class Base {
public:
// non-static member function
void foo()
{
cout << "Thread using non-static member function "
"as callable"
<< endl;
}
// static member function
static void foo1()
{
cout << "Thread using static member function as "
"callable"
<< endl;
}
};

// Driver code
int main()
{
cout << "Threads 1 and 2 and 3 "
"operating independently"
<< endl;

// This thread is launched by using
// function pointer as callable
thread th1(foo, 3);

// This thread is launched by using
// function object as callable
thread th2(thread_obj(), 3);

// Define a Lambda Expression
auto f = [](int x) {
for (int i = 0; i < x; i++)
cout << "Thread using lambda"
" expression as callable\n";
};

// This thread is launched by using
// lambda expression as callable
thread th3(f, 3);

// object of Base Class
Base b;

thread th4(&Base::foo, &b);

thread th5(&Base::foo1);

// Wait for the threads to finish
// Wait for thread t1 to finish
th1.join();

// Wait for thread t2 to finish
th2.join();

// Wait for thread t3 to finish
th3.join();

// Wait for thread t4 to finish
th4.join();

// Wait for thread t4 to finish
th5.join();

return 0;
}