#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define THREAD_NUM 5
#define MUTEX_ENABLED 0
struct thread_ctx
{
int id;
pthread_t tid;
} ctx_arr[THREAD_NUM];
int fd;
pthread_mutex_t *mtx;
pthread_mutexattr_t *mtxattr;
void * t_worker(void *arg)
{
int i;
char buf[10];
struct thread_ctx *ctx = (struct thread_ctx *)arg;
sprintf(buf, "%d\n", ctx->id);
if (MUTEX_ENABLED)
pthread_mutex_lock(mtx);
// critical section
for (i = 0; i < 4; i++)
{
write(fd, buf, strlen(buf));
usleep(100);
}
if (MUTEX_ENABLED)
pthread_mutex_unlock(mtx);
return (void *)ctx;
}
int main()
{
int i;
void *res;
// open file
fd = open("result.dat", O_CREAT|O_RDWR);
if (fd < 0)
{
printf("[ERROR] file open failure - %s.\n", strerror(fd));
return -1;
}
// init mutex
mtx = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
mtxattr = (pthread_mutexattr_t *)malloc(sizeof(pthread_mutexattr_t));
pthread_mutexattr_init(mtxattr);
pthread_mutexattr_settype(mtxattr, PTHREAD_MUTEX_TIMED_NP);
pthread_mutex_init(mtx, mtxattr);
for (i = 0; i < THREAD_NUM; i++)
{
ctx_arr[i].id = i;
if (pthread_create(&ctx_arr[i].tid, NULL, t_worker,
(void *)(ctx_arr + i)) != 0)
{
printf("[ERROR] pthread_create failure\n");
}
}
// To join all threads.
for (i = 0; i < THREAD_NUM; i++)
{
pthread_join(ctx_arr[i].tid, &res);
}
printf("[MSG] All threads are joined.\n");
close(fd);
free(mtx);
free(mtxattr);
return 0;
}
result :
cat result.dat # mutex off
2
1
0
1
0
1
3
0
1
2
3
4
4
4
4
3
4
4
4
4
cat result.dat # mutex on
1
1
1
1
0
0
0
0
2
2
2
2
3
3
3
3
4
4
4
4
No comments:
Post a Comment