| synchronized |
|
grammar |
| |
A control statement used in a multi-threaded script to mark area of
critical code which more than one thread should not execute at the
same time.
Generally, the expression associated with this statement
should be an object, which can be thought of as a token that only one
thread can possess at any given time.
Whichever thread has possession
of that token is allowed to execute the associated statements.
If the
token is not available, the thread will wait until it becomes available.
Care should be taken to avoid constructing situations wherein deadlock
can occur.
Namely, it is possible to construct situations where one
thread has lock A and it waiting for lock B, while another thread has
lock B and is waiting for lock A and so both threads wait indefinitely.
Its usage description can be summarized as follows:
Statement:
synchronized ( Expression ) Statement
| |
| Example: |
In the following forced example, two thread and the main thread all wish to
increment the same counter, which occurs in an orderly fashion due to the
synchronized
statements, which all involve the same lock object.
import yoix.stdio.*;
import yoix.thread.*;
Object lock = "lock";
int count = 0;
Thread thread_1 = {
run() {
int i;
printf("thread_1: started\n");
for(i=0; i<2; i++) {
printf("thread_1: request lock\n");
synchronized(lock) {
printf("thread_1: got lock (%d)\n",
count);
count++;
sleep(2);
}
printf("thread_1: released lock (%d)\n",
count);
}
}
};
Thread thread_2 = {
run() {
int i;
printf("thread_2: started\n");
for(i=0; i<2; i++) {
printf("thread_2: request lock\n");
synchronized(lock) {
printf("thread_2: got lock (%d)\n",
count);
count++;
sleep(3);
}
printf("thread_2: released lock (%d)\n",
count);
}
}
};
thread_1.run();
thread_2.run();
int i;
for(i=0; i<2; i++) {
printf("main: request lock\n");
synchronized(lock) {
printf("main: got lock (%d)\n", count);
count++;
sleep(5);
}
printf("main: released lock (%d)\n", count);
}
The output looks like:
thread_1: started
thread_1: request lock
thread_1: got lock (0)
thread_2: started
thread_2: request lock
main: request lock
thread_1: released lock (1)
thread_1: request lock
thread_2: got lock (1)
thread_2: released lock (2)
thread_2: request lock
main: got lock (2)
main: released lock (3)
main: request lock
thread_1: got lock (3)
thread_1: released lock (4)
thread_2: got lock (4)
thread_2: released lock (5)
main: got lock (5)
main: released lock (6)
| | |
| See Also: |
reference,
Thread
|
|
Yoix is a registered trademark of AT&T Inc.
|