레이블이 locale인 게시물을 표시합니다. 모든 게시물 표시
레이블이 locale인 게시물을 표시합니다. 모든 게시물 표시

2007년 4월 4일 수요일

쓰레드별 POSIX locale

홈디렉토리를 정리하다가 예전에 쓰레드별로 다른 로케일 쓰는 방법을 찾아보다가 작성했던 예제 코드 발견.  glibc 전용이긴 하지만 지금 서치해 보니 darwin에도 구현되어 있다.  (MS에는 GetThreadLocale, SetThreadLocale 따위, 꼭 필요한 상황은 많지 않다 보니 그다지 쓰이지는 않는 듯...)

#define _GNU_SOURCE

#include <pthread.h>
#include <locale.h>
#include <time.h>
#include <stdlib.h>

struct tm tm = { 0, };

void *
thread_func()
{
  char buf[256];
  int n;
  locale_t l;

  l = newlocale(LC_ALL_MASK, "ko_KR.UTF-8", 0);
 
  uselocale(l);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  uselocale(LC_GLOBAL_LOCALE);
  freelocale(l);
}

int
main(int argc, char *argv[])
{
  pthread_t t;
  char buf[256];
  int n;

  setlocale(LC_ALL, "C");

  pthread_create(&t, 0, thread_func, 0);
  pthread_detach(t);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
  sleep(1);
  n = strftime(buf, 256, "%b %A %a", &tm);
  buf[n] = '\0';
  puts(buf);
 
}

실행해 보면 이렇게 두 개 스레드가 다른 로케일을 사용한다.

$ ./a.out
Jan Sunday Sun
 1월 일요일 일
Jan Sunday Sun
 1월 일요일 일
Jan Sunday Sun
 1월 일요일 일
Jan Sunday Sun