metal-cos/tests/pthreadtest.c

95 lines
1.9 KiB
C
Raw Normal View History

2015-02-02 07:56:45 +00:00
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
2015-02-02 21:04:43 +00:00
pthread_mutex_t mtx;
2015-02-02 07:56:45 +00:00
void *
thread_simple(void *arg)
{
printf("thread_simple %p!\n", arg);
return arg;
}
2015-02-02 21:04:43 +00:00
void *
thread_lock(void *arg)
{
int i;
int status;
for (i = 0; i < 100; i++) {
status = pthread_mutex_lock(&mtx);
assert(status == 0);
pthread_yield();
status = pthread_mutex_unlock(&mtx);
assert(status == 0);
}
return NULL;
}
2015-02-02 07:56:45 +00:00
int
main(int argc, const char *argv[])
{
2015-02-02 21:04:43 +00:00
int i;
2015-02-02 07:56:45 +00:00
int status;
pthread_t thr;
void *result;
printf("PThread Test\n");
// Simple thread test
printf("simple test\n");
status = pthread_create(&thr, NULL, thread_simple, NULL);
assert(status == 0);
status = pthread_join(thr, &result);
assert(status == 0);
assert(result == NULL);
// Return value test
printf("return value test\n");
status = pthread_create(&thr, NULL, thread_simple, (void *)1);
assert(status == 0);
status = pthread_join(thr, &result);
assert(status == 0);
assert(result == (void *)1);
// Mutex test
2015-02-02 21:04:43 +00:00
printf("simple mutex lock test\n");
status = pthread_mutex_init(&mtx, NULL);
assert(status == 0);
status = pthread_mutex_lock(&mtx);
assert(status == 0);
status = pthread_mutex_unlock(&mtx);
assert(status == 0);
status = pthread_mutex_destroy(&mtx);
assert(status == 0);
// Mutex Contention Test
printf("contended mutex lock test\n");
pthread_mutex_init(&mtx, NULL);
status = pthread_create(&thr, NULL, thread_simple, (void *)1);
assert(status == 0);
for (i = 0; i < 100; i++) {
status = pthread_mutex_lock(&mtx);
assert(status == 0);
pthread_yield();
pthread_mutex_unlock(&mtx);
assert(status == 0);
}
status = pthread_join(thr, &result);
assert(status == 0);
status = pthread_mutex_destroy(&mtx);
assert(status == 0);
2015-02-02 07:56:45 +00:00
printf("Success!\n");
return 0;
}