Skip to content

Instantly share code, notes, and snippets.

@Djuki
Last active December 15, 2015 16:59
Show Gist options
  • Save Djuki/5292977 to your computer and use it in GitHub Desktop.
Save Djuki/5292977 to your computer and use it in GitHub Desktop.
PingPong synchronization with main thread in several programming languages
/*
Ping pong threads in c++ by Ivan Djurdjevac
Run this code with g++ 4.x
Command is:
g++ -std=c++0x -pthread main.cpp
Read output with
./a.out
/**/
#include <iostream>
#include <thread>
using namespace std;
// Ping pong function for thread
void ping_pong(string name) {
for (int i = 0; i < 3; ++i) {
std::cout << name << "\n" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::thread ping_t, pong_t;
std::cout << "Ready… Set… Go!\n";
//Launch ping and pong threads
ping_t = std::thread(ping_pong, "Ping!");
pong_t = std::thread(ping_pong, "Pong!");
ping_t.join();
pong_t.join();
std::cout << "Done!\n";
return 0;
}
class PingPongThread extends Thread {
/**
* Message for print
*/
private String message;
/**
* Main Application thread
*/
private Thread program;
/**
* Counter for active running threads
*/
static int threadsRunning = 0;
/**
* Create thread
*
* @param msg Message
* @param main Main Application thread
*/
public PingPongThread(String msg, Thread main) {
this.message = msg;
this.program = main;
++threadsRunning;
}
@Override
public void run ()
{
try {
for (int row = 1; row < 5; row++)
{
System.out.println (this.message);
Thread.sleep(1000);
}
} catch (Exception e)
{
e.printStackTrace();
} finally {
// When thread don with his work decrement number of running threads
--threadsRunning;
// If there is no active threads We can notify main thread to continue
if (threadsRunning <= 0)
this.notifyMain();
}
}
public void notifyMain() {
synchronized (program) {
try {
program.notify();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class PingPong {
public static void main(String[] args) {
PingPongThread ping = new PingPongThread("Ping!", Thread.currentThread());
PingPongThread pong = new PingPongThread("Pong!", Thread.currentThread());
System.out.println("Ready… Set… Go!");
ping.start();
pong.start();
waitPingPong(ping);
System.out.println("Done!");
}
/**
* Wait until ping pong threads are done
* @param ping
*/
public static void waitPingPong(Thread ping) {
synchronized (ping) {
try {
ping.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment