« Previous : 1 : 2 : 3 : 4 : 5 : Next »

SVN external로 세팅하기

가끔 svn을 사용하다 보면 한 프로젝트에서 전혀 다른 곳의 repository에 있는 파일들을 가져다 사용 해야 될 때가 있습니다.
이를 일일히 update 한 뒤 수작업으로 copy 하고 실행하고.. 를 반복 해도 되지만, 이 방법에도 한계가 있죠.

svn에서는 이러한 상황에서 사용할 수 있는, external로 연결하는 기능을 제공하고 있습니다.
이 기능을 사용하기 위해서는

1. checkout 원하는 project checkout
2. 추가하길 원하는 곳으로 이동
3. 다음의 명령어를 실행
svn propedit svn:externals .
3-1. 만약 svn: None of the environment variables SVN_EDITOR, VISUAL or EDITOR are set, and no 'editor-cmd' run-time configuration option was found 와 같은 메시지가 표시 된다면,
export SVN_EDITOR="vim"
와 같이 입력 후 재시도
4. 편집기에서 <디렉토리 경로> <svn 주소> 와 같이 편집. 예를 들어, 현재 디렉토리에 http://path.to/svn 의 내용을 abc 디렉토리에 넣고자 한다면
abc http://path.to/svn
와 같이 작성

svn update 하였을 때 "Updated external to revision xxxx"와 같이 표시되면 성공
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2011/09/16 16:16 2011/09/16 16:16
Response
7 Trackbacks , No Comment
RSS :
http://b4you.net/blog/rss/response/261

C#에서 UNIX_TIMESTAMP 형식 사용하기

UNIX_TIMESTAMP는 1970년 1월 1일 부터 해당 날짜까지 몇 초가 지났는지를 의미한다.
이러한 원리를 알고 있다면 변환하는 방법은 쉽다.
그냥 1970년 1월 1일을 나타내는 DateTime객체를 생성해서 더하거나 빼면 되는 것이다.

이러한 원이를 이용하여 다음과 같은 유틸리티를 만들어두면 편리하다.

public static DateTime DateTimeFromUnixTimeStamp(int unixTimeStamp)
{
    return new DateTime(1970, 1, 1).AddSeconds(unixTimeStamp);
}
public static int UnixTimeStampFromDateTime(DateTime dateTime)
{
    return (int)((dateTime - new DateTime(1970, 1, 1)).TotalSeconds);
}

참 쉽죠잉?
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/02 15:23 2009/06/02 15:23
, ,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/228

C#에서 INI 파싱하기

C#에는 INI parser가 없더군요???
구글링 하다보니... native api로 끌어다 쓰는게 있던데..
최대한 native 쓰지 말자! 라는 생각에 (혹시나 다른 플랫폼에서 돌릴 기회가 있으면 뿌듯해 하려고) 그냥 짰습니다.

덕분에 app header, key, value 등에 ~!@#$%^&*()_+와 같은 문자들을 전부 다 입력해보고.. GetPrivateProfileString()에서 제대로 파싱 되는지 분석해봤습니다.

손가락 2개로 짠거라 버그가 있을지도 모르니 사용하시다가 이상한 점이 있다면 피드백 부탁드립니다. (__)


크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/01 21:30 2009/06/01 21:30
,
Response
No Trackback , 6 Comments
RSS :
http://b4you.net/blog/rss/response/227

.NET에서 singleton class 만들기

Implementing the Singleton Pattern in C#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance=null;

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                lock (padlock)
                {
                    if (instance==null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }
    
    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.

Thanks to Andriy Tereshchenko for raising this issue.

A word on performance

A lot of the reason for this page stemmed from people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I've written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It's not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. That means that if you're "only" acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance - so improving it isn't going to do a lot. Now, if you are acquiring the singleton that often - isn't it likely you're using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.

I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.

Conclusion (modified slightly on January 7th 2006)

There are various different ways of implementing the singleton pattern in C#. A reader has written to me detailing a way he has encapsulated the synchronization aspect, which while I acknowledge may be useful in a fewvery particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called). I don't personally see that situation coming up often enough to merit going further with on this page, but please mail me if you're in that situation.

My personal preference is for solution 4: the only time I would normally go away from it is if I needed to be able to call other static methods without triggering initialization, or if I needed to know whether or not the singleton has already been instantiated. I don't remember the last time I was in that situation, assuming I even have. In that case, I'd probably go for solution 2, which is still nice and easy to get right.

Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides seem to only be rarely useful.

(I wouldn't use solution 1 because it's broken, and I wouldn't use solution 3 because it has no benefits over 5.)

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/29 16:27 2009/05/29 16:27
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/226

TLS 변수 초기화 하기

TLS(Thread Local Storage)를 사용하기 위해 변수를 초기화 하려면 다음과 같은 방법을 이용하면 됩니다.

1. API 사용
DWORD dwTlsIndex;
LPVOID pData;

dwTLSIndex = TlsAlloc();

if(dwTLSIndex != TLS_OUT_OF_INDEXES)
{
	pData = (LPVOID)LocalAlloc(LPTR, 256);

	TlsSetValue(dwTlsIndex, pData);

	TlsFree(dwTlsIndex);

	CommonFunc();

	pData = TlsGetValue(dwTlsIndex);

	if(pData != NULL)
	{
		LocalFree((HLOCAL)pData);
	}
}


2. compiler keyword 사용
_declspec(thread) int g_nCount;

2번의 경우 .tls section을 이용하여 구현이 된다고 하는데, 방법이 더 쉽긴 하지만 dll의 경우 process에 attach/detach될 때 문제가 발생할 수 있기 때문에 1번을 사용하여야 된다고 합니다.
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/11 20:07 2009/05/11 20:07
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/222

VS2005에서 dialog-based 프로젝트를 생성한 뒤에 보면 "잘못된 글꼴입니다" 뭐 이런식으로 나와서..

짜증나게 하는데 이럴 때 아래와 같이 바꿔주면 된다고 하는군요.

[버그재구성]

  1. 새 프로젝트(New Project)를 만들때 MFC 관련 프로젝트를 선택하여 생성한다.
  2. 위저드(App Wizard)에서 한글 리소스를 선택한다.
  3. 리소스 파일(.rc)을 클릭해서 리소스 뷰(Resource View)를 연다.
  4. 생성된 대화 상자(Dialog) 리소스를 선택하여 에디터를 연다.
  5. 버튼(Button)등을 추가했다가 삭제한다.

[버그내용]

생성된 대화 상자(Dialog)에서  컨트롤을 삭제할 시에 매번 무관한 에러 "Bad font face.(글꼴이 잘못되었습니다.)"가 발생한다. 문제가 되는 대화 상자가 생성되는 경우는 정보 대화 상자(About Box)와 대화 상자 기반 MFC Application의 대화 상자등 위저드(Wizard)가 생성한 대화 상자들이다. 새로 추가하는 대화 상자(Dialog) 리소스는 해당되지 않는다.

[버그원인]

위저드(Wizard)에서 프로젝트를 생성하기 위해 사용하는 템플릿에는 다이알로그 리소스가 "MS Shell Dlg"라는 폰트 Face를 사용하도록 설정되어있다. 폰트 Face이기 때문에 번역되지 말아야할 이 부분이 "MS 셸 대화 상자"로 잘못 번역되어 존재하지 않는 폰트 Face로 인식하여 오류가 발생하게 된다.

[버그해결방안]

VS2005를 설치한 드라이브의 \Program Files\Microsoft Visual Studio 8\VC\VCWizards\AppWiz\MFC\Application\templates\1042 디렉토리를 열고 all.rc와 dlg.rc에서 "MS 셸 대화 상자"를 "MS Shell Dlg"로 치환(Replace)한다.



것.. 참... 웃깁니다.

http://blogs.msdn.com/bkchung/archive/2005/10/10/478990.aspx
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/04/13 14:08 2009/04/13 14:08
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/215

멀티 프로세서 이용하기

#pragma omp section
#pragma omp parallel...
을 이용하여 멀티 프로세서를 사용함으로써 효율을 높일 수 있다. 출처 및 예제: http://deadwi.jaram.org/wiki/wikka.php?wakka=OpenMPSections/show&time=2008-09-08+17:55:15
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2008/10/23 09:50 2008/10/23 09:50
, , ,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/178

STL 에서 exception catch 하기

STL에서(여기서는 vector) 값의 범위가 넘어가거나 기타 오류가 발생하였을 때 _THROW로 exception을 throw하는데,
이것을 받기 위해서는 아래와 같이 코딩하면 된다.

vector<int> a;

a.push_back(10);
a.push_back(20);
a.push_back(30);

_TRY_BEGIN
  v = a.at(0);
_CATCH(out_of_range)
  printf("Error\n");
_CATCH_END

알겠지만 _CATCH()안에 catch할 exception을 쓰면 된다.

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2007/12/28 13:25 2007/12/28 13:25
,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/159

O(n)을 O(1)로 만들자.

몇일 전(어제였나?^^;) 친구에게도 했던 말이다.

일반적으로 귀차니즘에 의해 코딩을 하게 되면 복잡도가 O(n)이 되는 것 같다.
왜? 속도에 신경을 안쓰니까.
linkedlist도 신경안쓰고 짜면 원소 추가의 속도가 O(n)이 되버린다.
이걸 원소 나열이나 검색과 같이 사용한다면.. O(n^2)이 되버리니 끔찍하다.

그렇다면 어떻게 속도를 빠르게 할 수 있을까?

마지막 노드 뒤에 값을 추가하고 싶으면 처음부터 마지막 노드를 찾을 게 아니라 마지막 노드를 미리 저장해놓는것이다.
그러면 마지막까지 가지 않아도 되니 O(1)의 속도가 나온다.
즉, 현재 상태를 저장하는 방법이 있다는 것이다.
(전혀 쌩뚱맞은데다가 비유가 되지 않는 말이겠지만.. 프로그램이 실행 될 때 레지스터 값 등의 context를 저장한 뒤 context switching을 통하여 다중 프로세스를 실행하기도 한다. 이렇게 저장하듯이 자주 사용되는 데이터들의 값을 backup해놓으면 속도가 향상된다는것이다. 아무래도 이건 비유가 엉성하다 -ㅅ-)

김상형-API프로그래밍 #2 책을 보면, 당근이라는 프로그램을 만들면서 속도에 대한 이야기가 나온다.
글꼴 정보를 얻기 위해 연산하는 overhead가 매우 크므로 이것을 배열에 저장해두면 몇 KB를 소비하면서 속도는 굉장히 빨라진다고. (책에서 아마 5배 빨라진다고 했던 것 같다.)
sin도 마찬가지로, sin값을 미리 구해놓으면 CPU입장에서 손이 많이가는 float연산을 줄일 수 있으니 많이 빨리질 수 있다.

그냥 볼 땐 정말 당연하지만.. 실제로 코딩할 때 간단한 루틴임에도 불구하고 O(1)의 속도를 보장하지 못한다면..
게다가 자주 사용되는 루틴이라면.. O(n^3) 이상이 될지도 모른다.

문득 O(1)이 될 수 있는 O(n) 코드를 보면서 적는다. API나 함수는 잘 생각해보고 짜자.
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2007/11/29 22:45 2007/11/29 22:45
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/154

printf(str)과 printf("%s", str)의 차이점

* 이번 글은 초보자를 위한 글입니다.

가끔 디버깅을 목적으로 printf(str); 와 같이 작성을 할 때가 있다.
그럼 printf("%s", str); 과 뭐가 다르지?

우선 다음과 같은 코드가 있다고 가정 해 보자.

int main() { char *str = "1234"; printf(str); return 0; }


출력이 잘 된다.
그러면 아래와 같이 바꿔보자.

int main() { char *str = "1234%d"; printf(strd); return 0; }


결과는?

이런 현상이 발생하는건 printf의 첫번째 인자는 "format" 이라는 형식이기 때문이다.
따라서 일반 문자열 처리하는데는 지장이 없지만, escape 문자를 처리할 때에는 문제가 발생할 수 있다.

따라서 printf("%s", str); 이나 puts(str)로 해야한다.

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2007/11/02 11:31 2007/11/02 11:31
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/148

« Previous : 1 : 2 : 3 : 4 : 5 : Next »

블로그 이미지

빗소리를 먹는 사람.

- 장현준

Notices

Archives

Authors

  1. 장현준

Recent Trackbacks

Calendar

«   2017/10   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        

Site Stats

Total hits:
1805188
Today:
1462
Yesterday:
4622