void *thread_function(void *dummyPtr) {
	//printf("Thread number %ld\n", mypthread_self());
	mypthread_mutex_lock(&mutex1);
	counter++;
	mypthread_mutex_unlock(&mutex1);
	mypthread_exit(NULL);
}
int main(int argc, char *argv[]) {
	if (argc != 2) {
		printf("usage: %s mypthread_policy(0|1|2|3)\n", argv[0]);
		exit(0);
	}
	mypthread_init(atoi(argv[1]));
	mypthread_mutex_init(&mutex1, NULL);
	mypthread_t thread_id[NTHREADS];
	int i, j;

	for (i = 0; i < NTHREADS; i++) {
		mypthread_create(&thread_id[i], NULL, thread_function, NULL);
	}

	for (j = 0; j < NTHREADS; j++) {
		mypthread_join(thread_id[j], NULL);
	}

	/* Now that all threads are complete I can print the final result.     */
	/* Without the join I could be printing a value before all the threads */
	/* have been completed.                                                */

	printf("Final counter value: %d\n", counter);
	mypthread_exit(NULL);
}
void *fnsort(void *arg) {
    struct pthrarg *pargs;
    int *num, swap;
    mypthread_mutex_t *mtx0, *mtx1;

    pargs = (struct pthrarg *) arg;
    num = pargs->num;
    mtx0 = pargs->mtx;
    mtx1 = pargs->mtx + 1;

    while (!quitting) {
        mypthread_mutex_lock(mtx0);
        if (mypthread_mutex_trylock(mtx1) != 0) {
            mypthread_mutex_unlock(mtx0);
            mypthread_yield();
            continue;
        }

        if (num[1] < num[0]) {
            swap = num[0];
            num[0] = num[1];
            num[1] = swap;
        }

        mypthread_mutex_unlock(mtx0);
        mypthread_mutex_unlock(mtx1);

        mypthread_yield();
    }

    mypthread_exit(0);

    // I will never get here
    return 0;
}
void destroy_threadpool(threadpool destroyme) {
	_threadpool *pool = (_threadpool *) destroyme;
	void* nothing;
	int i = 0;
	free(pool->threads);

	mypthread_mutex_destroy(&(pool->mutex));
	mypthread_cond_destroy(&(pool->cond));
	mypthread_exit(NULL);
	return;
}
Beispiel #5
0
void * fncheck( void *arg )
{
    struct pthrarg *pargs;
    int i, j = 0, size, check;
    mypthread_mutex_t *mtx;

    pargs = (struct pthrarg * )arg;
    mtx   = pargs->mtx;
    size  = pargs->size;

    while( !quitting )
    {
        printf( "." );
        if( (j+1) % 80 == 0 )
            printf( "\n" );

        //lock all threads
        for( i = 0; i < size; i++ )
            mypthread_mutex_lock( mtx+i );

        check = 1;
        for( i = 0; i < size-1 && check; i++ )
        {
            if( pargs->num[i] > pargs->num[i+1] )
                check = 0;
        }

        if( check )
            printf("\nQuitting...\n");
        quitting = check;

        //unlock all threads
        for( i = 0; i < size; i++ )
            mypthread_mutex_unlock( mtx+i );

        // j seconds
        j = j+1;
#ifndef MYTHREAD
       // sleep( j );
#endif
        mypthread_yield( );
    }

    mypthread_exit( 0 );

    return 0;
}