-
Notifications
You must be signed in to change notification settings - Fork 0
/
progress_bar.c
94 lines (76 loc) · 1.84 KB
/
progress_bar.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#define NUMBER_OF_BARS 5
#define PROG_BAR_LENGTH 30
#define NUMBER_OF_THREADS 5
typedef void* (*func)(void*);
#define false 0;
#define true 1;
typedef struct
{
pthread_t thread;
int count_to_val;
int progress;
func thread_func;
}thread_info;
void update_bar(thread_info *thread)
{
int num_chars = (thread->progress * 100 / thread->count_to_val) * PROG_BAR_LENGTH / 100;
printf("[");
for(int i = 0; i<num_chars; i++)
{
printf("-");
}
for(int i = 0; i<PROG_BAR_LENGTH - num_chars; i++)
{
printf(" ");
}
printf("]\n");
}
void *some_func(void *arg)
{
thread_info *thread = (thread_info*)arg;
for (thread->progress = 0;
thread->progress < thread->count_to_val;
thread->progress++)
{
usleep(1000);
}
return NULL;
}
int main()
{
printf("starting bar threads example...\n");
thread_info threads[NUMBER_OF_THREADS];
for (int i=0; i<NUMBER_OF_THREADS; i++)
{
threads[i].count_to_val = rand() % 1000;
threads[i].progress = 0;
threads[i].thread_func = some_func;
pthread_create(&(threads[i].thread), NULL, threads[i].thread_func, &threads[i]);
}
printf("threads created...\n");
_Bool done = false;
while (!done)
{
done = true;
for (int i=0; i<NUMBER_OF_THREADS; i++)
{
update_bar(&threads[i]);
if (threads[i].progress <threads[i].count_to_val)
{
done = false;
}
}
if (!done)
{
printf("\033[5F");
}
usleep(1000);
}
printf("Done!\n");
}