Last active
July 11, 2021 20:27
-
-
Save exbotanical/e187ce42eadaaf2a1eeabb0d36fe9604 to your computer and use it in GitHub Desktop.
demonstration of 'transfer of computation' (POSIX threads)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sysexits.h> | |
#include <errno.h> | |
// this code snippet demonstrates the 'transfer of computation' methodology, | |
// whereby two threads do not transfer data but a computation that acts upon | |
// this observed data | |
// we demonstrate this via a global value `global_v`; | |
// where `thread_i` awaits `global_v`'s assignment to a specific value, and provides | |
// `thread_ii` with a computation to perform the assignment | |
// compiled as `gcc transfer_of_computation.c -o main -lpthread` | |
/* global state, which will be toggled by the transferred computation */ | |
int global_v; | |
/* initialized 'shared computation'*/ | |
void (*shared_fn)(int x, int y) = NULL; | |
/* multiply assigns the global state to the awaited value*/ | |
void multiply(int x, int y) { | |
global_v = x * y; | |
} | |
/** | |
* @brief Waits for the shared function, invoking it once available | |
* | |
* @param arg | |
* @return void* | |
*/ | |
void* thread_i_fn(void* arg) { | |
while (!shared_fn); | |
printf("Shared function now available to thread %ld\n", pthread_self()); | |
shared_fn(3, 3); | |
return NULL; | |
} | |
/** | |
* @brief Waits for the shared, global state to change to the expected value | |
* | |
* @param arg | |
* @return void* | |
*/ | |
void* thread_ii_fn(void* arg) { | |
shared_fn = multiply; | |
printf("Thread %ld has transferred the computation\n", pthread_self()); | |
while (global_v != 9); | |
printf("The global state is now available as %d to thread %ld\n", global_v, pthread_self()); | |
return NULL; | |
} | |
int main(int argc, char* argv[]) { | |
pthread_t thread_i, thread_ii; | |
if (pthread_create(&thread_i, NULL, thread_i_fn, NULL) != 0 || | |
pthread_create(&thread_ii, NULL, thread_ii_fn, NULL) != 0) { | |
return EX_CANTCREAT; | |
} | |
pthread_join(thread_i, NULL); | |
pthread_join(thread_ii, NULL); | |
return EX_OK; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment