What is "thread"
Thread is a sequence of programmed instructions that can be managed independently by the OS process scheduler. A thread is usually contained within a process and a process can contain more than one thread.
A thread allows, for example, the user of a program to use an environment functionality while other execution lines perform other calculations and operations.
Systems that support only a single thread (in actual execution) are called monothread while systems that support multiple threads are called multithreaded.
Examples of threads in some programming languages:
Java
import java.util.logging.Level;
import java.util.logging.Logger;
class Threaded extends Thread {
Synchronized1 base;
public Threaded( Synchronized1 bse ) {
this.base = bse;
}
}
public class Synchronized1 {
public Synchronized1() {
}
public void ini() {
new Threaded( this ) {
public void run() {
while( true ) {
synchronized( base ) {
System.out.print( "Este é A, agora vai mostrar B.\n" );
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
base.notify();
base.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
new Threaded( this ) {
public void run() {
while( true ) {
synchronized( base ) {
System.out.print( "Este é B, então foi já mostrado A.\n" );
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
base.notify();
base.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
}
public static void main(String[] args) {
new Synchronized1().ini();
}
}
C
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREADS_MAX 4
void *function(void *param)
{
int id = (int)param;
int i, loops = 10;
for(i = 0; i < loops; i++)
{
printf("thread %d: loop %d\n", id, i);
}
pthread_exit(NULL);
}
int main(void)
{
pthread_t threads[THREADS_MAX];
int i;
printf("pre-execution\n");
for (i = 0; i < THREADS_MAX; i++)
{
pthread_create(&threads[i], NULL, function, (void *)i);
}
printf("mid-execution\n");
for (i = 0; i < THREADS_MAX; i++)
{
pthread_join(threads[i], NULL);
}
printf("post-execution\n");
return EXIT_SUCCESS;
}
Ruby
count = 0
a = Thread.new { loop { count += 1 } }
sleep(0.1)
Thread.kill(a)
puts count #=> 93947