Skip to content

Instantly share code, notes, and snippets.

@dulimarta
Last active January 31, 2018 17:09
Show Gist options
  • Save dulimarta/a7e25cb3984e5d2b8e16 to your computer and use it in GitHub Desktop.
Save dulimarta/a7e25cb3984e5d2b8e16 to your computer and use it in GitHub Desktop.
CS452 Thread Examples (.java, .c, .cpp)
#include <pthread.h>
#include <stdio.h>
void* happy (void* arg) {
int* N = (int *)arg;
for (int k = 0; k < *N; k++)
printf ("Happy %d\n", k);
return (void *) 0xF00D;
}
int main () {
pthread_t happy_id;
pthread_attr_t happy_attr;
pthread_attr_init (&happy_attr);
int num;
num = 6;
pthread_create (&happy_id, &happy_attr, happy, &num);
for (int k = 0; k < 20; k++)
printf ("Before %d\n", k);
int rc;
pthread_join (happy_id, (void **) &rc);
printf ("Thread status is %x\n", rc);
printf ("End of program\n");
return 0;
}
// Must be compiled with -std=c++11 flag
#include <iostream>
#include <string>
#include <thread>
#include <future>
std::string happy(int N) {
for (int k = 0; k < N; k++)
std::cout << "HAPPY " << k << std::endl;
return "Happyly ever after";
}
int main() {
int val = 20;
// Use std::async to create a thread
// Use std::future to capture the thread return value
std::future<std::string> happy_end ( std::async(happy, val));
for (int k = 0; k < 20; k++) {
std::cout << "grumpy " << k << std::endl;
}
// wait for the "happy" thread to complete
std::string out = happy_end.get();
std::cout << "New value is " << val << std::endl;
std::cout << "Happy value is " << out << std::endl;
return 0;
}
public class Happy {
private static class HappyThread extends Thread {
private int limit;
public HappyThread(int N) {
this.limit = N;
}
public void run() {
try {
for (int k = 0; k < limit; k++) {
Thread.sleep (1000);
System.out.printf ("Happy %d\n", k);
}
} catch (InterruptedException e) {
}
}
};
public static void main (String[] args) {
Thread t = new HappyThread(7);
try {
t.start();
for (int k = 0; k < 15; k++) {
for (int m = 0; m < 10000000; m++);
System.out.printf ("Main %d\n", k);
}
System.out.println ("Waiting for HappyThread.....");
t.join();
}
catch (InterruptedException ie) {
}
System.out.println ("End of program");
}
}
#include <pthread.h>
#include <stdio.h>
void* happy (void* arg) {
int* N = (int *)arg;
for (int k = 0; k < *N; k++)
printf ("Happy %d\n", k);
return (void *) 0xF00D;
}
int main () {
pthread_t happy_id;
pthread_attr_t happy_attr;
pthread_attr_init (&happy_attr);
int num;
num = 6;
pthread_create (&happy_id, &happy_attr, happy, &num);
for (int k = 0; k < 20; k++)
printf ("Before %d\n", k);
int rc;
pthread_join (happy_id, (void **) &rc);
printf ("Thread status is %x\n", rc);
printf ("End of program\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment