Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- int* thread_counts;
- pthread_t* threads;
- int tcount = 0;
- pthread_mutex_t mutex;
- void* threadAction(void* arg) {
- int tid;
- pthread_mutex_lock(&mutex);
- tid=tcount;
- tcount++;
- pthread_mutex_unlock(&mutex);
- while (1) {
- pthread_mutex_lock(&mutex);
- thread_counts[tid]++;
- pthread_mutex_unlock(&mutex);
- }
- }
- int main(int argc, char *argv[]) {
- int error, n_threads;
- if (argc < 2) {
- printf("USAGE: %s NUM_THREADS\n", argv[0]);
- return 1;
- }
- n_threads = atoi(argv[1]);
- thread_counts = malloc(sizeof(int) * n_threads);
- threads = malloc(sizeof(int) * n_threads);
- if (pthread_mutex_init(&mutex, NULL) != 0) {
- printf("Could not initialize mutex");
- return 1;
- }
- for (int i=0; i < n_threads; i++) {
- error = pthread_create(&(threads[i]), NULL, &threadAction, NULL);
- if (error != 0) {
- printf("Error creating thread %u", i);
- return 1;
- }
- }
- printf("Set everything up, sleeping now...\n");
- sleep(1);
- for (int i=0; i < n_threads; i++) {
- thread_counts[i] = 0;
- }
- sleep(3);
- for (int i=0; i < n_threads; i++) {
- printf("Counter %u has value %u\n", i, thread_counts[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement