kazuyamaa/multi-language-messages-01 huggingface dataset:
Task: Append a record to the end of a text file
Go: package main

import (
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "os"
)

type pw struct {
    account, password string
    uid, gid          uint
    gecos
    directory, shell string
}

type gecos struct {
    fullname, office, extension, homephone, email string
}

func (p *pw) encode(w io.Writer) (int, error) {
    return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n",
        p.account, p.password, p.uid, p.gid,
        p.fullname, p.office, p.extension, p.homephone, p.email,
        p.directory, p.shell)
}


var p2 = []pw{
    {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007",
        "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"},
        "/home/jsmith", "/bin/bash"},
    {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004",
        "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"},
        "/home/jsmith", "/bin/bash"},
}

var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003",
    "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"},
    "/home/xyz", "/bin/bash"}

var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," +
    "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash"

const pfn = "mythical"

func main() {
    writeTwo()
    appendOneMore()
    checkResult()
}

func writeTwo() {
    
    f, err := os.Create(pfn)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer func() {
        if cErr := f.Close(); cErr != nil && err == nil {
            fmt.Println(cErr)
        }
    }()
    for _, p := range p2 {
        if _, err = p.encode(f); err != nil {
            fmt.Println(err)
            return
        }
    }
}

func appendOneMore() {
    
    f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0)
    if err != nil {
        fmt.Println(err)
        return
    }
    if _, err := pa.encode(f); err != nil {
        fmt.Println(err)
    }
    if cErr := f.Close(); cErr != nil && err == nil {
        fmt.Println(cErr)
    }
}

func checkResult() {
    
    b, err := ioutil.ReadFile(pfn)
    if err != nil {
        fmt.Println(err)
        return
    }
    if string(bytes.Split(b, []byte{'\n'})[2]) == expected {
        fmt.Println("append okay")
    } else {
        fmt.Println("it didn't work")
    }
}

PHP: <?php

$filename = '/tmp/passwd';

$data = array(
    'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL,
    'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL,
    'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL,
);
file_put_contents($filename, $data, LOCK_EX);

echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;

$data = array(
    'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL
);
file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);

echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Task: Append a record to the end of a text file
Python: 



passwd_list=[
  dict(account='jsmith', password='x', UID=1001, GID=1000, 
       GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917',
                  homephone='(234)555-0077', email='jsmith@rosettacode.org'),
                  directory='/home/jsmith', shell='/bin/bash'),
  dict(account='jdoe', password='x', UID=1002, GID=1000,
       GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914',
                  homephone='(234)555-0044', email='jdoe@rosettacode.org'),
       directory='/home/jdoe', shell='/bin/bash')
]

passwd_fields="account password UID GID GECOS directory shell".split()
GECOS_fields="fullname office extension homephone email".split()

def passwd_text_repr(passwd_rec):

  passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields])
  for field in passwd_rec: 
    if not isinstance(passwd_rec[field], str):
      passwd_rec[field]=`passwd_rec[field]`
  return ":".join([ passwd_rec[field] for field in passwd_fields ])

passwd_text=open("passwd.txt","w")
for passwd_rec in passwd_list:
  print >> passwd_text,passwd_text_repr(passwd_rec)
passwd_text.close()




passwd_text=open("passwd.txt","a+")
new_rec=dict(account='xyz', password='x', UID=1003, GID=1000,
             GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913',
                        homephone='(234)555-0033', email='xyz@rosettacode.org'),
             directory='/home/xyz', shell='/bin/bash')
print >> passwd_text,  passwd_text_repr(new_rec)
passwd_text.close()




passwd_list=list(open("passwd.txt","r"))
if "xyz" in passwd_list[-1]:
  print "Appended record:",passwd_list[-1][:-1]

PHP: <?php

$filename = '/tmp/passwd';

$data = array(
    'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL,
    'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL,
    'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL,
);
file_put_contents($filename, $data, LOCK_EX);

echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;

$data = array(
    'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL
);
file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);

echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Task: Append a record to the end of a text file
VB: 
$Include "Rapidq.inc"

dim file as qfilestream
dim filename as string
dim LogRec as string


filename = "C:\Logfile2.txt"
file.open(filename, fmCreate)
file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash"
file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash"
file.close


file.open(filename, fmOpenWrite)
file.position = File.size
file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash"
file.close


file.open (filename, fmOpenRead)
while not file.EOF
    LogRec = File.Readline
wend
file.close

showmessage "Appended record: " + LogRec

PHP: <?php

$filename = '/tmp/passwd';

$data = array(
    'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL,
    'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL,
    'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL,
);
file_put_contents($filename, $data, LOCK_EX);

echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;

$data = array(
    'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL
);
file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);

echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Task: Metered concurrency
C: #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

sem_t sem;
int count = 3;


#define getcount() count
void acquire()
{
	sem_wait(&sem);
	count--;
}

void release()
{
	count++;
	sem_post(&sem);
}

void* work(void * id)
{
	int i = 10;
	while (i--) {
		acquire();
		printf("#%d acquired sema at %d\n", *(int*)id, getcount());
		usleep(rand() % 4000000); 
		release();
		usleep(0);  
	}
	return 0;
}

int main()
{
	pthread_t th[4];
	int i, ids[] = {1, 2, 3, 4};

	sem_init(&sem, 0, count);

	for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
	for (i = 4; i--;) pthread_join(th[i], 0);
	printf("all workers done\n");

	return sem_destroy(&sem);
}

C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}
Task: Metered concurrency
C: #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

sem_t sem;
int count = 3;


#define getcount() count
void acquire()
{
	sem_wait(&sem);
	count--;
}

void release()
{
	count++;
	sem_post(&sem);
}

void* work(void * id)
{
	int i = 10;
	while (i--) {
		acquire();
		printf("#%d acquired sema at %d\n", *(int*)id, getcount());
		usleep(rand() % 4000000); 
		release();
		usleep(0);  
	}
	return 0;
}

int main()
{
	pthread_t th[4];
	int i, ids[] = {1, 2, 3, 4};

	sem_init(&sem, 0, count);

	for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
	for (i = 4; i--;) pthread_join(th[i], 0);
	printf("all workers done\n");

	return sem_destroy(&sem);
}

C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}
Task: Metered concurrency
C: #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

sem_t sem;
int count = 3;


#define getcount() count
void acquire()
{
	sem_wait(&sem);
	count--;
}

void release()
{
	count++;
	sem_post(&sem);
}

void* work(void * id)
{
	int i = 10;
	while (i--) {
		acquire();
		printf("#%d acquired sema at %d\n", *(int*)id, getcount());
		usleep(rand() % 4000000); 
		release();
		usleep(0);  
	}
	return 0;
}

int main()
{
	pthread_t th[4];
	int i, ids[] = {1, 2, 3, 4};

	sem_init(&sem, 0, count);

	for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
	for (i = 4; i--;) pthread_join(th[i], 0);
	printf("all workers done\n");

	return sem_destroy(&sem);
}

Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()
Task: Metered concurrency
C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}

C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}
Task: Metered concurrency
C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}

Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}
Task: Metered concurrency
C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}

Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}
Task: Metered concurrency
C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}

Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()
Task: Metered concurrency
C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}

VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Metered concurrency
C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}

Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}
Task: Metered concurrency
C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}

Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}
Task: Metered concurrency
C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}

Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()