Skip to content

Instantly share code, notes, and snippets.

@mangalaman93
Created August 25, 2017 23:30
Show Gist options
  • Save mangalaman93/95516c67df1a0e9ab21cb77194f2ac26 to your computer and use it in GitHub Desktop.
Save mangalaman93/95516c67df1a0e9ab21cb77194f2ac26 to your computer and use it in GitHub Desktop.
Threads printing string in circular fashion
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
mutex mut;
condition_variable* cond;
// Points to the current thread who is allowed to print
int cur_thread_index = 0;
// Prints a given string in cicular fashion if the
// index is bigger than the length of the string
void circular_print(char* str, int thread_index, int str_index, int char_count) {
int n = strlen(str);
str_index = str_index % n;
cout<<"Thread "<<thread_index<<" ";
while (char_count > 0) {
if (char_count <= n - str_index) {
cout.write(str+str_index, char_count);
char_count = 0;
str_index += char_count;
} else {
cout.write(str+str_index, n-str_index);
char_count -= n - str_index;
str_index = 0;
}
}
cout<<endl;
}
void print(int index, char* str, int char_count, int num_threads, int k) {
int count = 0;
while (count < k) {
unique_lock<std::mutex> lk(mut);
while(index != cur_thread_index) {
cond[index].wait(lk);
}
int my_str_index = (count*num_threads+index)*char_count;
circular_print(str, index, my_str_index, char_count);
cur_thread_index = (cur_thread_index + 1) % num_threads;
count++;
cond[(index+1) % num_threads].notify_one();
}
}
int main() {
char* str = new char[100];
int char_count, num_threads, k;
cin>>str>>char_count>>num_threads>>k;
cond = new condition_variable[num_threads];
thread* t = new thread[num_threads];
for (int i = 0; i < num_threads; ++i) {
t[i] = thread(print, i, str, char_count, num_threads, k);
}
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
delete[] t;
delete[] cond;
delete[] str;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment