Download (참고) Java Threads - Marvel

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lab 3 Threads
• ~mysung/thread/pthread.c 프로그램과 ~mysung/thread/thread.c
프로그램을 코딩하여 실행해 보세요.
» /usr/include/pthread.h 와 /usr/include/thread.h 참조
• pthread Summation 프로그램을 코딩하여 실행해 보세요.
• Windows XP thread (Win32 thread) Summation 프로그램을 코딩하여
실행해 보세요.
자식 스레드를 만들어 자식 스레드로 하여금 리눅스에서는 “$ ls -al” 을,
윈도우 환경에서는 “> dir /a” 명령을 수행시키는 프로그램을 아래
버전으로 각각 만들어 숙제 디렉토리에 제출하세요.  과제 4
» pthread 버전
» Win32 thread 버전
운영체제
4.1
인천대학교 컴퓨터공학과 성미영
pthreads (thrd-posix.c)
#include <pthread.h>
#include <stdio.h>
int sum; /* this data is shared by the thread(s) */
void *runner(void *param); /* the thread */
main(int argc, char *argv[])
{
pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of attributes for the thread */
/* get the default attributes */
pthread_attr_init(&attr);
/* create the thread */
pthread_create(&tid,&attr,runner,argv[1]);
/* now wait for the thread to exit */
pthread_join(tid,NULL);
printf("sum = %d\n",sum);
}
void *runner(void *param) {
int upper = atoi(param);
int i;
sum = 0;
if (upper > 0) {
for (i = 1; i <= upper; i++)
sum += i;
}
pthread_exit(0);
}
운영체제
4.2
인천대학교 컴퓨터공학과 성미영
Win32 Threads
/**
* This program creates a separate thread using the
CreateThread() system c
*
* Figure 4.10
*
* @author Gagne, Galvin, Silberschatz
* Operating System Concepts - Eighth Edition
* Copyright John Wiley & Sons - 2009.
*/
int main(int argc, char *argv[])
{
DWORD ThreadId;
HANDLE ThreadHandle;
int Param;
// do some basic error checking
if (argc != 2) {
fprintf(stderr,"An integer parameter is required\n");
return -1;
}
#include <stdio.h>
#include <windows.h>
Param = atoi(argv[1]);
if (Param < 0) {
fprintf(stderr, "an integer >= 0 is required \n");
return -1;
}
DWORD Sum; /* data is shared by the thread(s) */
/* the thread runs in this separate function */
DWORD WINAPI Summation(PVOID Param)
{
DWORD Upper = *(DWORD *)Param;
// create the thread
ThreadHandle = CreateThread(NULL, 0, Summation,
&Param, 0, &ThreadId);
for (DWORD i = 0; i <= Upper; i++)
Sum += i;
}
return 0;
}
운영체제
4.3
if (ThreadHandle != NULL) {
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
printf("sum = %d\n",Sum);
}
인천대학교 컴퓨터공학과 성미영
Java Threads
•
•
Java threads are managed by the JVM
•
Java Thread 생성
① Thread class로부터 새 class 유도하고 run() 재정의
• start()가 (1) 메모리 할당하고 새 thread 초기화, (2)
run() 실행
• 절대로 직접 run()호출하지 말고 start()를 호출할 것!
(초기화 때문)
② Runnable interface를 구현하는 class를 정의하고 새
Thread 객체
• 주로 class가 이미 유도된 경우 이용
(예) public class ThreadedApplet extends Applet
implements Runnable { … }
• Java는 multiple inheritance 불가
운영체제
Java threads may be created by:
» Extending Thread class
» Implementing the Runnable interface
4.4
인천대학교 컴퓨터공학과 성미영
Thread class 확장으로 thread 생성
class Worker1 extends Thread
{
public void run() {
System.out.println(“I am a Worker Thread”);
}
}
public class First
{
public static void main(String args[]) {
Worker runner = new Worker1();
runner.start();
System.out.println(“I am the main thread”);
}
}
운영체제
4.5
인천대학교 컴퓨터공학과 성미영
Runnable interface를 구현하여 thread 생성
public interface Runnable
{
public abstract void run();
}
/* Runnable interface 코딩 않음 */
class Worker2 implements Runnable
{
public void run() {
System.out.println(“I am a Worker Thread”);
}
}
public class Second
{
public static void main(String args[]) {
Runnable runner = new Worker2();
Thread thrd = new Thread(runner);
thrd.start();
}
}
운영체제
System.out.println(“I am the main thread”);
4.6
인천대학교 컴퓨터공학과 성미영
Java Threads
• Thread 관리
» Java의 thread 관리 APIs
• suspend()
• sleep()
• resume()
• stop()
» multithreading 예: applet
• 일반적으로 graphics, animation, audio 등 처리
• 처음 applet 실행될 때 start(), display 않는 동안 stop()
• ClockApplet 참조
• Thread 상태
»
»
»
»
운영체제
New: new 문으로 thread 객체 생성
Runnable: start() 호출로 메모리 할당하고 run() 호출한 상태
Blocked: I/O, sleep(), suspend()로 block된 상태
Dead: stop() 호출된 상태
4.7
인천대학교 컴퓨터공학과 성미영
Applet
•
•
•
standalone application : 지금까지 본 자바 프로그램들
applet : web page에 삽입되어 실행되는 자바 프로그램
» No main()
» Constructor: init()
AppletViewer FirstApplet.html 로 실행
•
•
FirstApplet.java 파일
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
public void init(){
//initialization code goes here
}
}
FirstApplet.html 파일
<applet
Code = FirstApplet.class
Width = 400
Height = 200>
</applet>
public void paint(Graphics g){
g.drawString(“Java Primer Now Brewing!”,15,15);
}
운영체제
4.8
인천대학교 컴퓨터공학과 성미영
날짜와 시간을 출력하는 ClockApplet
public void stop() {
if(clockThread != null)
clockThread.suspend() ;
}
import java.applet.* ;
import java.awt.* ;
public class ClockApplet extends Applet
implements Runnable {
public void run() {
while(true) {
try {
Thread.sleep(1000);
}
catch(InterruptedException e) { }
repaint();
}
}
public void destroy() {
if(clockThread != null) {
clockThread.stop() ;
clockThread = null ;
}
}
public void paint(Graphics g) {
g.drawString(new java.util.Date().toString(),
10, 30) ;
}
public void start() {
if(clockThread == null) {
clockThread = new Thread(this);
private Thread clockThread;
clockThread.start() ;
}
} else
clockThread.resume();
}
운영체제
4.9
<applet
code = ClockApplet
width = 250
height = 50>
</applet>
인천대학교 컴퓨터공학과 성미영
Java Threads
• Thread와 JVM
» JVM의 system-level threads
• garbage-collector thread
• timer events handling thread: sleep()
• graphics control thread: 버튼 입력, 스크린 갱신
• JVM과 호스트 OS
» Java threads = user threads
» JVM이 Java threads 관리
• Windows NT: one-to-one model
• Solaris 2.1~2.5: many-to-one model
• Solaris 2.6~: many-to-many model
• Multithreaded 해법 예제: Mailbox(IPC)를 이용하는 생산자-소비자 문제
» The class Server 참조
» Producer thread 참조
» Consumer thread 참조
운영체제
4.10
인천대학교 컴퓨터공학과 성미영
Java Thread States
운영체제
4.11
인천대학교 컴퓨터공학과 성미영
Driver.java
class Sum
public class Driver
{
{
private int sum;
public static void main(String[] args) {
public int get() {
if (args.length != 1) {
return sum;
System.err.println("Usage Driver <integer>");
}
System.exit(0);
public void set(int sum) {
}
this.sum = sum;
}
Sum sumObject = new Sum();
}
int upper = Integer.parseInt(args[0]);
class Summation implements Runnable
{
Thread worker = new Thread(new Summation(upper, sumObject));
private int upper;
worker.start();
private Sum sumValue;
try {
public Summation(int upper, Sum sumValue) {
worker.join();
if (upper < 0)
} catch (InterruptedException ie) { }
throw new IllegalArgumentException();
System.out.println("The sum of " + upper + " is " +
sumObject.get());
this.upper = upper;
}
this.sumValue = sumValue;
}
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.set(sum);
}
}
운영체제
4.12
인천대학교 컴퓨터공학과 성미영
Threading Issues
•
Semantics of fork() and exec() system calls
»
Does fork() duplicate only the calling thread or all threads?
•
목표 스레드(target thread; 취소되어야 할 스레드)의 스레드 종료(Thread cancellation )
»
비동기식 취소(Asynchronous cancellation): 즉시 목표 스레드를 강제 종료
»
지연 취소(Deferred cancellation): 목표 스레드가 주기적으로 강제 종료되어야 할 지를 체크
•
시그널 처리(Signal handling)
»
A signal handler is used to process signals
•
디폴트 신호 처리기
•
사용자 정의 신호 처리기
»
어느 스레드에게 전달?
•
신호가 적용될 스레드에게
•
모든 스레드에게
•
몇몇 스레드에게
•
특정 스레드가 전달 받도록 지정
•
스레드 풀(Thread pools)
»
새 스레드를 만들기 보다 기존 스레드로 서비스하는 것이 빠름: Win32API PoolFunction()
»
존재할 스레드 개수에 제한을 둠
•
스레드별 데이터(Thread-specific data)
»
각 스레드가 자기 자신만의 데이터를 가짐
»
스레드 풀 사용 등 스레드를 생성할 수 없을 때 유리함
•
스케줄러 액티베이션(Scheduler activations)
»
다대다 모델(Many-to-Many models)과 두수준 모델(Two-level models) 은 응용에 할당할 커널
스레드를 적정 수준으로 유지하기 위한 통신 필요
»
스케줄러 액티베이션 방법은 커널 스레드로부터 스레드 라이브러리로의 통신 메커니즘 upcalls 지원
»
LWP = 가상처리기(virtual processor)
4.13
인천대학교 컴퓨터공학과 성미영
(참고) Java Threads: Extending the Thread Class
class Worker1 extends Thread
{
public void run() {
System.out.println("I Am a Worker Thread");
}
}
public class First
{
public static void main(String args[]) {
Worker1 runner = new Worker1();
runner.start();
System.out.println("I Am The Main Thread");
}
}
운영체제
4.14
인천대학교 컴퓨터공학과 성미영
(참고) Java Threads: The Runnable Interface
•
The Runnable Interface
public interface Runnable
{
public abstract void run();
}
•
Implementing the Runnable Interface
class Worker2 implements Runnable
{
public void run() {
System.out.println("I Am a Worker Thread ");
}
}
public class Second
{
public static void main(String args[]) {
Runnable runner = new Worker2();
Thread thrd = new Thread(runner);
thrd.start();
System.out.println("I Am The Main Thread");
}
}
운영체제
4.15
인천대학교 컴퓨터공학과 성미영
(참고) Java Threads: Joining Threads
class JoinableWorker implements Runnable
{
public void run() {
System.out.println("Worker working");
}
}
public class JoinExample
{
public static void main(String[] args) {
Thread task = new Thread(new JoinableWorker());
task.start();
try { task.join(); }
catch (InterruptedException ie) { }
System.out.println("Worker done");
}
}
운영체제
4.16
인천대학교 컴퓨터공학과 성미영
(참고) Java Threads: Thread Cancellation
•Thread Cancellation 2
•Thread Cancellation 1
public class InterruptibleThread implements Runnable
{
public void run() {
public class CancelExample
while (true) {
{
/**
public static void main(String[] args)
* do some work for awhile
{
*/
Thread thrd = new Thread (new InterruptibleThread());
thrd.start();
if (Thread.currentThread().isInterrupted()) {
System.out.println("I'm interrupted!");
break;
}
// now interrupt it
thrd.interrupt();
}
}
}
// clean up and terminate
}
}
운영체제
4.17
인천대학교 컴퓨터공학과 성미영
(참고) Thread Specific Data
•Thread Specific Data 1
•Thread Specific Data 2
class Service
{
private static ThreadLocal errorCode = new ThreadLocal();
class Worker implements Runnable
{
private static Service provider;
public void run() {
provider.transaction();
System.out.println(provider.getErrorCode());
}
public static void transaction() {
try {
/**
* some operation where an error may occur
*/
}
catch (Exception e) {
errorCode.set(e);
}
}
}
/**
* get the error code for this transaction
*/
public static Object getErrorCode() {
return errorCode.get();
}
}
운영체제
4.18
인천대학교 컴퓨터공학과 성미영
Related documents