Using trylock:
FILE *fp; pthread_mutex_t demoMutex; void * printHello (void* threadId) { pthread_mutex_trylock (&demoMutex); pthread_t writeToFile = pthread_self (); unsigned short iterate; for (iterate = 0; iterate < 10000; iterate++) { fprintf (fp, " %d ", iterate, 4); fprintf (fp, " %lu ", writeToFile, sizeof (pthread_t)); fprintf (fp, "\n", writeToFile, 1); } pthread_mutex_unlock (&demoMutex); pthread_exit (NULL); }
and then main ():
int main () { pthread_t arrayOfThreadId [5]; int returnValue; unsigned int iterate; fp = fopen ("xyz", "w"); pthread_mutex_init (&demoMutex, NULL); for (iterate = 0; iterate < 5; iterate++) { if (returnValue = pthread_create (&arrayOfThreadId [iterate], NULL, printHello, (void*) &arrayOfThreadId [iterate]) != 0) { printf ("\nerror: pthread_create failed with error number %d", returnValue); } } for (iterate = 0; iterate < 5; iterate++) pthread_join (arrayOfThreadId [iterate], NULL); return 0; }
Here, the first output prints some of the first stream, and then the rest, and then again the first. The lock does not work. If I replace the same with pthread_mutex_lock
, each thing will be shown very sequentially!
What ridiculous mistake is here?
source share