Last active
December 3, 2017 02:35
-
-
Save garcia556/3b403e6403acbdb9d0c6acce0c8a9a2f to your computer and use it in GitHub Desktop.
Simple example of threads running simultaneously
This file contains hidden or 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 <stdio.h> | |
#include <string.h> | |
#include <pthread.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#define EXIT_TIMEOUT 1 | |
#define THREAD_COUNT 3 | |
pthread_t tid[THREAD_COUNT]; | |
void* worker(void *arg) | |
{ | |
pthread_t id = pthread_self(); | |
int ix = -1; | |
for (int i = 0; i < THREAD_COUNT; i++) | |
if (pthread_equal(id, tid[i])) | |
ix = i + 1; | |
while (1) | |
printf("[%d]: Thread working ...\n", ix); | |
return NULL; | |
} | |
int main(void) | |
{ | |
int err; | |
for (int i = 0; i < THREAD_COUNT; i++) | |
{ | |
err = pthread_create(&(tid[i]), NULL, &worker, NULL); | |
if (err != 0) | |
printf("Error creation failed with error \"%s\"", strerror(err)); | |
else | |
printf("[%d]: Thread created successfully\n", i + 1); | |
} | |
sleep(EXIT_TIMEOUT); | |
printf("\n"); | |
return 0; | |
} |
This file contains hidden or 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
#!/bin/bash | |
# support macOS by default | |
function is_linux | |
{ | |
if [[ "$(uname)" == "Linux" ]]; then | |
echo 1 | |
return | |
fi | |
echo 0 | |
} | |
OUT="output.log" | |
APP="pthreads_example.out" | |
SRC=$(ls *.c) | |
CFLAGS="" | |
PS="ps -M " | |
if [[ "$(is_linux)" == "1" ]]; then | |
CFLAGS="-pthread" | |
PS="ps -Lf -p " | |
fi | |
cc ${CFLAGS} -o ${APP} ${SRC} | |
./${APP} > ${OUT} & | |
PID=$(ps x | grep -v grep | grep ${APP} | awk '{$1=$1;print}' | cut -d ' ' -f 1) | |
${PS} ${PID} | |
sleep 1 | |
head -n 20 ${OUT} | |
tail -n 20 ${OUT} | |
rm ${APP} ${OUT} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment