The code :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define NUM_THREADS 8
typedef struct {
int id;
int *ptr_arr;
pthread_t thread;
pthread_mutex_t mutex;
} some_struct;
void *some_func (void *arg)
{
some_struct *w = (some_struct *)arg;
/* do I really need to lock? */
pthread_mutex_lock(&w->mutex);
w->ptr_arr[w->id] = w->id * 4;
pthread_mutex_unlock(&w->mutex);
}
int main (void)
{
int arr[NUM_THREADS];
int cnt;
some_struct ss[NUM_THREADS];
/* initialize */
for (cnt = 0; cnt < NUM_THREADS; ++cnt) {
arr[cnt] = cnt;
ss[cnt].id = cnt;
ss[cnt].ptr_arr = arr;
pthread_mutex_init(&ss[cnt].mutex, NULL);
}
/* print array */
for (cnt = 0; cnt < NUM_THREADS; ++cnt) {
printf("%3d%8d\n", cnt, arr[cnt]);
}
/* do something */
for (cnt = 0; cnt < NUM_THREADS; ++cnt) {
pthread_create(&ss[cnt].thread, NULL, some_func, &ss[cnt]);
}
/* join the threads */
for (cnt = 0; cnt < NUM_THREADS; ++cnt) {
pthread_join(ss[cnt].thread, NULL);
}
printf("\n");
/* print them again */
for (cnt = 0; cnt < NUM_THREADS; ++cnt) {
printf("%3d%8d\n", cnt, arr[cnt]);
}
return(0);
}
The explanation:
As you can see, there are 8 threads. Each of them is modifying a single area of an array according to the thread id.
The question:
Do I really need to lock the mutex?