- 论坛徽章:
- 0
|
本帖最后由 kelvenchi 于 2013-05-04 22:01 编辑
- #! /usr/bin/perl
- use strict;
- use warnings;
- use threads;
- use threads::shared;
- use Socket;
- use Thread::Semaphore;
- use Thread::Queue;
- if (my $pid = fork) {
- exit;
- } elsif ($pid = fork) {
- setpgrp;
- exit;
- } else {
- my $fd = Thread::Queue->new();
- my $rabbish = Thread::Queue->new();
- my $sem = shared_clone(Thread::Semaphore->new(5));
- my $lis = threads->create(\&boss);
- my $jt = threads->create(\&joinThread);
- sub worker {
- my $fino = $fd->dequeue;
- while (1) {
- my @in;
- open my $fhh, "<tserver.pl" or die "$!";
- @in = <$fhh>;
- close $fhh or die "$!";
- open my $fh, ">&=$fino" or die "$!";
- while (@in) {
- my $single = shift @in;
- print $fh "$single";
- }
- print $fh "this message is from the server $ and the tid is " . threads->self->tid . "\n";
- close $fh or die "$!";
- }
- }
- sub joinThread {
- while (my $j = $rabbish->dequeue()) {
- $j->detach;
- $sem->up;
- }
- }
- sub boss {
- socket Server, AF_INET, SOCK_STREAM, getprotobyname 'tcp';
- setsockopt Server, SOL_SOCKET, SO_REUSEADDR, 1;
- my $paddr = sockaddr_in 9001, INADDR_ANY;
- bind Server, $paddr;
- listen Server, SOMAXCONN;
- while (accept my $Client , Server) {
- my $t;
- $t = threads->create(\&worker) if $sem->down_nb();
- $rabbish->enqueue($t) if $t;
- $fd->enqueue(fileno $Client)if $t;
- undef $t;
- close $Client;
- }
- }
- $lis->join;
- $jt->join;
- }
复制代码 |
|