Multi thread in c
c
C / C++
// gcc -pthread th.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *entry_point(void *value) {
int *num = (int *) value;
int nth = *num;
printf("thread%d (id : %ld) are run!\n", nth, pthread_self());
if (*num > 3) {
*num += 400;
pthread_exit(value);
}
if (*num == 3) *num += 200;
long i = 0;
long d = 100000000;
long max = (*num==1)? 100000000000 : 1000000000;
while(i < max) {
if (i%d == 0) printf("msg from thread%d (i = %ld)\n", nth, i);
i++;
}
if (*num == 203) *num += 10;
else if (*num <= 2) *num += 200;
}
int main(int argc, char **argv) {
pthread_t thread1;
pthread_t thread2;
printf("main thread (id : %ld) are run!\n", pthread_self());
// 4 for test thread exit
// 1 for test normal thread
int num1 = 1;
// 3 for test thread change args value without exit
// 2 for cancel first thread
int num2 = 2;
pthread_create(&thread1, NULL, entry_point, &num1);
pthread_create(&thread2, NULL, entry_point, &num2);
//// for join one thread (wait end of this thread for continue)
//pthread_join(thread1, NULL);
while (1) {
if (num2 > 200 && num2 < 400) pthread_cancel(thread1);
if (num2 == 202 || num2 == 213) break;
}
printf("arg thread1 : %d, arg thread2 : %d\n", num1, num2);
printf("close main thread\n");
return EXIT_SUCCESS;
}
main thread (id : 140324940408640) are run!
thread1 (id : 140324940404480) are run!
msg from thread1 (i = 0)
thread2 (id : 140324932011776) are run!
msg from thread2 (i = 0)
msg from thread2 (i = 100000000)
msg from thread1 (i = 100000000)
msg from thread2 (i = 200000000)
msg from thread1 (i = 200000000)
msg from thread2 (i = 300000000)
msg from thread1 (i = 300000000)
msg from thread2 (i = 400000000)
msg from thread1 (i = 400000000)
msg from thread2 (i = 500000000)
msg from thread1 (i = 500000000)
msg from thread2 (i = 600000000)
msg from thread1 (i = 600000000)
msg from thread2 (i = 700000000)
msg from thread1 (i = 700000000)
msg from thread2 (i = 800000000)
msg from thread1 (i = 800000000)
msg from thread2 (i = 900000000)
msg from thread1 (i = 900000000)
arg thread1 : 1, arg thread2 : 202
close main thread
thread1 (id : 140324940404480) are run!
msg from thread1 (i = 0)
thread2 (id : 140324932011776) are run!
msg from thread2 (i = 0)
msg from thread2 (i = 100000000)
msg from thread1 (i = 100000000)
msg from thread2 (i = 200000000)
msg from thread1 (i = 200000000)
msg from thread2 (i = 300000000)
msg from thread1 (i = 300000000)
msg from thread2 (i = 400000000)
msg from thread1 (i = 400000000)
msg from thread2 (i = 500000000)
msg from thread1 (i = 500000000)
msg from thread2 (i = 600000000)
msg from thread1 (i = 600000000)
msg from thread2 (i = 700000000)
msg from thread1 (i = 700000000)
msg from thread2 (i = 800000000)
msg from thread1 (i = 800000000)
msg from thread2 (i = 900000000)
msg from thread1 (i = 900000000)
arg thread1 : 1, arg thread2 : 202
close main thread