반응형

스레드 클래스를 상속받는 클래스를 정의하고 사용해 보자.

 

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
32
33
34
35
36
37
38
39
import time
import threading
 
class Worker(threading.Thread):
    def __init__(self, name, count, delay):
        super().__init__()
        self.name = name
        self.count = count
        self.delay = delay
 
    # 스레드 클래스를 상속하는 클래스는 run()를 재정의 해야 한다.
    # 객체를 만들고 start()를 실행하면 run()가 실행된다.
    def run(self):
        print(f"{self.name} job started.")
        for i in range(self.count):
            print(f"{self.name} job: {i}.")
            time.sleep(self.delay)
        print(f"{self.name} job finished.")
 
            
print("Main started.")
 
thread_1 = Worker("First"50.5)
#thread_1.daemon = True
# 데몬 스레드로 설정되면 메인 스레드 종료시 서브 스레드도 종료된다.
thread_1.start()
#thread_1.join()
# join()을 실행한 스레드가 종료할 때까지 나머지 스레드는 대기한다.
 
thread_2 = Worker("Second"50.5)
#thread_2.daemon = True
thread_2.start()
#thread_2.join()
 
print(f"■ Number of threads: {threading.active_count()}")
 
time.sleep(1)
 
print("Main finished.")
 

 

 

 

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
import time
import threading
 
class Worker(threading.Thread):
    def __init__(self, name, count, delay):
        super().__init__()
        self.name = name
        self.count = count
        self.delay = delay
        
    def run(self):
        print(f"{self.name} job started.")
        for i in range(self.count):
            print(f"{self.name} job: {i}.")
            time.sleep(self.delay)
        print(f"{self.name} job finished.")
 
thread_1 = Worker("First"50.5)
thread_2 = Worker("Second"50.5)
thread_3 = Worker("Third"50.5)
threads = [thread_1, thread_2, thread_3]
 
print(f"■ Number of threads: {threading.active_count()}")
# 활성화된 스레드는 메인스레드 뿐이므로 1이 표시된다.
 
for thread in threads:
    thread.start()
    thread.join()
 

 

 

 

thread - Thread-based parallelism

 

반응형
Posted by J-sean
:

C# Type Class 타입 클래스

C# 2022. 7. 20. 00:12 |
반응형

Type 클래스를 사용해 보자.

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Reflection;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Type t = typeof(String);
            //Type t = Type.GetType("System.String");
            String str = "";
            Type t = str.GetType();
            // Gets a Type object that represents the specified type.
 
            MethodInfo[] methods = t.GetMethods();
            foreach (MethodInfo method in methods)
            {
                // String 클래스의 Substring 함수는 2개의 오버로딩 함수가 있다.
                if (method.Name == "Substring")
                {
                    Console.WriteLine("- Method: " + method.Name);
 
                    ParameterInfo[] parameters = method.GetParameters();
                    foreach (ParameterInfo parameter in parameters)
                    {
                        Console.WriteLine("Parameter: " + parameter.Name);
                    }
                }
            }
 
            Console.WriteLine();
 
            MethodInfo substr = t.GetMethod("Substring"new Type[] { typeof(int), typeof(int) });
            // Searches for the specified method whose parameters match the specified generic
            // parameter count, argument types and modifiers, using the specified binding constraints.
 
            Object result = substr.Invoke("Hello, World!"new Object[] { 75 });
            // Invokes the method or constructor represented by the current instance, using the
            // specified parameters.
 
            Console.WriteLine("{0} returned \"{1}\".", substr, result);
        }
    }
}
 

 

소스를 빌드하고 실행한다.

 

 

반응형
Posted by J-sean
:
반응형

C#으로 클래스 라이브러리(DLL)를 만들어 보자.

 

Class Library (.NET Framework) 프로젝트를 선택한다.

 

적당한 이름과 위치를 지정한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSDll
{
    public class Class1
    {
        public static int Add(int a, int b)
        {
            return a + b;
        }
 
        public static int Sub(int a, int b)
        {
            return a - b;
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

클래스 라이브러리(DLL)가 생성된다.

 

 

마찬가지로 적당한 이름과 위치에 Console App (.NET Framework)을 생성한다.

 

위에서 생성한 라이브러리를 사용하기 위해 using 선언을 하면 에러가 발생한다. 사용하려는 라이브러리를 찾을 수 없기 때문이다.

 

Project - Add Reference... 를 선택한다.

 

Browse에서 Browse... 버튼을 클릭한다.

 

 

사용하려는 라이브러리 파일을 선택하고 Add 버튼을 클릭한다.

 

라이브러리가 추가되면 OK 버튼을 클릭한다.

 

에러 표시가 사라졌다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using CSDll;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("3 + 2 = {0}", Class1.Add(32));
            Console.WriteLine("3 - 2 = {0}", Class1.Sub(32));
        }
    }
}
 

 

라이브러리를 사용하는 코드를 입력하고 빌드한다.

 

 

문제없이 실행된다.

 

Output 폴더를 확인해 보면 라이브러리(CSDll.dll)가 복사되어 있다. 라이브러리 파일은 실행파일과 함께 배포해야 한다.

 

반응형
Posted by J-sean
: