The goal of this program is to copy a string taken in by user input word for word using multithreading. Each thread copies every fourth word so for instance the first thread copies the first and fifth words, the second copies the second and sixth words, etc. I have done quite a bit of research on mutex and I believe I have implemented the mutex lock properly however the string still comes up as jumbled nonsense when it prints. Can someone shed some light as to why the threads aren't synchronizing?
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *processString(void *);
char msg1[100];
char msg2[100];
char * reg;
char * token;
char * tokens[10];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t = PTHREAD_COND_INITIALIZER;
int main(){
int i = 0, j;
pthread_t workers[4];
printf("Please input a string of words separated by whitespace characters: \n");
scanf("%99[^\n]", msg1); //take in a full string including whitespace characters
//tokenize string into individual words
token = strtok(msg1, " ");
while(token != NULL){
tokens[i] = (char *) malloc (sizeof(token));
tokens[i] = token;
token = strtok(NULL, " ");
i++;
}
for(j = 0; j < 4; j++){
if(pthread_create(&workers[j], NULL, processString, (void *) j))
printf("Error creating pthreads");
}
for(i = 0; i < 4; i++){
pthread_join(workers[i], NULL);
}
pthread_mutex_destroy(&lock);
printf("%s\n", msg2);
return 0;
}
//each thread copies every fourth word
void *processString(void *ptr){
int j = (int) ptr, i = 0;
pthread_mutex_lock(&lock);
while(tokens[i * 4 + j] != NULL){
reg = (char *) malloc (sizeof(tokens[i * 4 + j]));
reg = tokens[i * 4 + j];
strcat(msg2, reg);
strcat(msg2, " ");
i++;
}
pthread_mutex_unlock(&lock);
return NULL;
}