[SDL] Re: threading overhead

Pierre Phaneuf pp at ludusdesign.com
Sun Apr 9 13:46:50 PDT 2000


Pierre Phaneuf wrote:

> I was expecting this, but I was wondering if any multithreading
> proponent had anything to say on my code?

Well, including the code could help, right? :-)

-- 
Pierre Phaneuf
http://ludusdesign.com/
-------------- next part --------------
#ifdef THREADED
#include <pthread.h>
#endif
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>

#define ITER 10000
#define BUFSIZE 65536

void* buf1;
void* buf2;
void* buf3;

#ifdef THREADED
pthread_mutex_t lock;

void* thread1(void* dummy) {
  unsigned int count;

  for(count = ITER; count > 0; count--) {
    pthread_mutex_lock(&lock);
    memcpy(buf3, buf1, BUFSIZE);
    pthread_mutex_unlock(&lock);
  }

  return NULL;
}

void* thread2(void* dummy) {
  unsigned int count;

  for(count = ITER; count > 0; count--) {
    pthread_mutex_lock(&lock);
    memcpy(buf3, buf2, BUFSIZE);
    pthread_mutex_unlock(&lock);
  }

  return NULL;
}
#else
void thread1() {
  memcpy(buf3, buf1, BUFSIZE);
}

void thread2() {
  memcpy(buf3, buf2, BUFSIZE);
}
#endif

int main(int argc, char** argv) {
#ifdef THREADED
  pthread_t t1;
  pthread_t t2;
#else
  unsigned int count;
#endif
  struct timeval time1;
  struct timeval time2;
  unsigned int msec;

  buf1 = malloc(BUFSIZE);
  buf2 = malloc(BUFSIZE);
  buf3 = malloc(BUFSIZE);

#ifdef THREADED
  pthread_mutex_init(&lock, NULL);
#endif

  if(gettimeofday(&time1, NULL) == -1) {
    perror(argv[0]);
    exit(1);
  }

#ifdef THREADED
  errno = pthread_create(&t1, NULL, thread1, NULL);
  if(errno != 0) {
    perror(argv[0]);
    exit(1);
  }

  errno = pthread_create(&t2, NULL, thread2, NULL);
  if(errno != 0) {
    perror(argv[0]);
    exit(1);
  }

  errno = pthread_join(t1, NULL);
  if(errno != 0) {
    perror(argv[0]);
    exit(1);
  }

  errno = pthread_join(t2, NULL);
  if(errno != 0) {
    perror(argv[0]);
    exit(1);
  }
#else
  for(count = ITER; count > 0; count--) {
    thread1();
    thread2();
  }
#endif

  if(gettimeofday(&time2, NULL) == -1) {
    perror(argv[0]);
    exit(1);
  }

  free(buf1);
  free(buf2);
  free(buf3);

#ifdef THREADED
  errno = pthread_mutex_destroy(&lock);
  if(errno != 0) {
    perror(argv[0]);
    exit(1);
  }
#endif

  msec = (time2.tv_sec - time1.tv_sec) * 1000;
  msec += (time2.tv_usec - time1.tv_usec) / 1000;

#ifdef THREADED
  printf("Running time: %i ms (multi-threaded)\n", msec);
#else
  printf("Running time: %i ms (single-threaded)\n", msec);
#endif

  return 0;
}


More information about the SDL mailing list