spBase
読み取り中…
検索中…
一致する文字列を見つけられません
thread_test.c
#include <stdio.h>
#include <stdlib.h>
#include <sp/spThread.h>
#define USE_MUTEX
//#undef USE_MUTEX
static int x = 0;
#ifdef USE_MUTEX
static void *mutex = NULL;
#endif
#define YIELD_INTERVAL 500
#define DISPLAY_INTERVAL 100
#define NUM_LOOP1 500
#define NUM_LOOP2 100000
spThreadReturn thread1(void *data)
{
int i, j, px;
for (i = 0; i < NUM_LOOP1; i++) {
if ((i % DISPLAY_INTERVAL) == 0) {
printf("thread1: i = %d\n", i);
}
#ifdef USE_MUTEX
spLockMutex(mutex);
#endif
px = x;
for (j = 0; j < NUM_LOOP2; j++) {
x++;
if (x - px != 1) {
printf("thread1 interrupted by other threads: x = %d, px = %d\n", x, px);
}
px = x;
if ((j % YIELD_INTERVAL) == 0) {
}
}
#ifdef USE_MUTEX
spUnlockMutex(mutex);
#endif
}
return SP_THREAD_RETURN_SUCCESS;
}
spThreadReturn thread2(void *data)
{
int i, j, px;
for (i = 0; i < NUM_LOOP1; i++) {
if ((i % DISPLAY_INTERVAL) == 0) {
printf("\tthread2: i = %d\n", i);
}
#ifdef USE_MUTEX
spLockMutex(mutex);
#endif
px = x;
for (j = 0; j < NUM_LOOP2; j++) {
x++;
if (x - px != 1) {
printf("\tthread2 interrupted by other threads: x = %d, px = %d\n", x, px);
}
px = x;
if ((j % YIELD_INTERVAL) == 0) {
}
}
#ifdef USE_MUTEX
spUnlockMutex(mutex);
#endif
}
return SP_THREAD_RETURN_SUCCESS;
}
int main(int argc, char *argv[])
{
void *hth1, *hth2;
long ret;
#ifdef USE_MUTEX
if ((mutex = spCreateMutex("test")) == NULL) {
fprintf(stderr, "mutex create error\n");
exit(1);
}
#endif
printf("create thread1\n");
if ((hth1 = spCreateThread(0, 0, thread1, NULL)) == NULL) {
fprintf(stderr, "can't create thread1\n");
exit(1);
}
printf("create thread2\n");
if ((hth2 = spCreateThread(0, 0, thread2, NULL)) == NULL) {
fprintf(stderr, "can't create thread1\n");
exit(1);
}
printf("wait thread1\n");
ret = spWaitThread(hth1);
printf("thread1 result: %ld\n", ret);
printf("wait thread2\n");
ret = spWaitThread(hth2);
printf("thread2 result: %ld\n", ret);
printf("done\n");
return 0;
}
void * spCreateThread(long stacksize, int priority, spThreadFunc func, void *data)
long spWaitThread(void *handle)
spBool spLockMutex(void *handle)
void * spCreateMutex(const char *name)
spBool spUnlockMutex(void *handle)
void spYieldThread(void)