Fils d'exécution (threads)

for ++i ou i++

2007-04-09

for (i = 0; i<5; i++) {} donne la même chose que for (i = 0; i<5; ++i) {}

Exemple de pthread.h

2009-01-24

/**
 * Show pthread_create and pthread_join 
 * @author Yan Morin
 * @creation 2009-01-24
 * @see http://zoonek2.free.fr/UNIX/30_UNIX_2000/pthreads.html
 */
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

void * thread_function(void *a) {
	int i;

	for (i = 0; i < 10; i++) {
		printf("Inside thread [%d]\n", i);
		usleep(100);
	}
}

int main(int argc, char* argv[]) {
	int i;
	pthread_t my_thread;
	printf("Before pthread_create\n");
	pthread_create(&my_thread, NULL, thread_function, NULL);

	/* bla bla */
	for (i = 0; i < 10; i++) {
		printf("After pthread_create [%d]\n", i);
		usleep(10);
	}

	/* wait for pthread end */
	pthread_join(my_thread, NULL);

	return 0;
}

pthread mutex

2009-01-24

/**
 * Show pthread_mutex_lock/unlock
 * @author Yan Morin
 * @creation 2009-01-24
 * @see http://zoonek2.free.fr/UNIX/30_UNIX_2000/pthreads.html
 */

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t fastmutex_for_long = PTHREAD_MUTEX_INITIALIZER;
long shared_long = 1;

void * thread_function(void *a) {
	int i;

	for (i = 0; i < 10; i++) {
		pthread_mutex_lock(&fastmutex_for_long);
		shared_long <<= 1;
		printf("Inside thread [i = %d, long = %ld]\n", i, shared_long);
		pthread_mutex_unlock(&fastmutex_for_long);
		usleep(100);
	}
}

int main(int argc, char* argv[]) {
	int i;
	pthread_t my_thread;
	printf("Before pthread_create\n");
	pthread_create(&my_thread, NULL, thread_function, NULL);

	/* bla bla */
	for (i = 0; i < 10; i++) {
		pthread_mutex_lock(&fastmutex_for_long);
		shared_long++;
		printf("After pthread_create [i = %d, long = %ld]\n", i, shared_long);
		pthread_mutex_unlock(&fastmutex_for_long);
		usleep(10);
	}

	/* wait for pthread end */
	pthread_join(my_thread, NULL);

	return 0;
}