/* * "THE CHEESE-WARE LICENSE" (Revision 1): * wrote this file. As long as you retain this notice * you can do whatever you want with this stuff. If we meet some day, * and you think this stuff is worth it, you can buy me some cheese * in return */ #include #include #include #include #include volatile unsigned long long global = 0; #define NR_THREADS 4 #define GLOBAL_STOP_VALUE 15 pthread_t threads[NR_THREADS] = {0}; void *thread_routine(void* args) { size_t arg = *((size_t *) args); // Так как на глобальном счетчике нет синхронизации, // количество выводов в консоль можен не совпадать с // GLOBAL_STOP_VALUE while (global < GLOBAL_STOP_VALUE) { printf("Hello from thread %lu\n", arg); global += 1; sleep(5); } pthread_exit(NULL); } int main() { for (size_t i = 0; i < NR_THREADS; i++) { size_t *arg = malloc(sizeof(*arg)); assert(arg); *arg = i; pthread_create(&threads[i], NULL, thread_routine, arg); } int ret; for (size_t i = 0; i < NR_THREADS; i++) { ret = pthread_join(threads[i], NULL); if (ret) { break; } } return 0; }