Perl Anyevent Simple Introduction and introductory knowledge _perl

Source: Internet
Author: User
Tags stdin


What is event-oriented programming (event-driven programming):



All programs in programming are determined by events – either by user action (keyboard, mouse) or by the arrival of other programs and streams or by operating system events, such as network packets, that can trigger execution.



Event-oriented programming can also be defined as writing a computer program in which the code (usually the head of the program's function) is explicitly assigned to the application's main loop, and its code itself consists of two parts: event and event-handling code.



Event-oriented programming is often applied in three situations:



1. Create control of the user interface (including graphics)
2. Create a server-based application
3. Management of multiple objects during game programming



When we manage systems, this application uses a lot of event-oriented programming in server applications, such as for server applications to solve 10,000 concurrent connections (so-called c10k issues)



Anyevent is a very good performance based event-driven program that someone uses to solve the c10k problem, as we usually write the program is based on the process. We all do the events first 1-> then do the event 2-> then do the event 3. This way.



But based on the event is completely different, in the main process you have only one main frame, the program action triggers are driven by events. For example, we use the window program. Minimizing the point maximization is based on events, When the program that receives the maximized event does the part of maximizing the event begins to run. It is not performed from the beginning to the end. So we read the event-based program and it's best to draw a mind map to help us understand.



The most common benefit of event-based programs is to do asynchronous, for example, we want to download 100 files and process them after downloading them. It is possible to write events for each download and process, which can be synchronized (the key is to wait while the network is connected and the read/write IO for the file). Events are for these waiting to be reused.
I don't know if you know about the Select feature in Perl, but wait until the handle can be read or written, do different reading or writing operations. The same is true for event loops.



Throughout the anyevent, we just focus on the two-point line, the Watchers (the monitor) and the condition variable.



Watchers (monitor)



In the Select, there is a role called "Monitor", which is the SELECT function itself.
Not only can you monitor IO in Anyevent, but you can also monitor other events. To do different things. We can be seen as someone who keeps staring at something.
There are several basic built-in things that can be used to stare ("monitor").
TIMER: Monitoring time, to a certain condition, and then to different time to do different events
I/O: This is to monitor whether IO can read and write, and then do the corresponding events
IDLE: What to do in your spare time
SIGNAL: Monitoring view of different information, call the corresponding event
Child process: invokes the appropriate handling event on the state of the Child program



TIMER watchers



Basic syntax





 code as follows:

Anyevent->timer (
After => $seconds, # How long to do the appropriate operation.
Interval => $seconds, # Once the above conditions are in effect, how often each cell callback.
CB => $CB, # CB is the abbreviation of callback, so know it, as long as the conditions in front, will run the CB => point function.
);





Use instance:



The following example is, 5 seconds later, every 2 seconds in the callback event, until $w the registered event is undef (that is, $count > 10). The undef $w in this case is the way to cancel this watcher.





 code as follows:

#!/usr/bin/perl
Use strict;
Use anyevent;

My $CV = anyevent->condvar;

my $count = 0;
my $w; $w = Anyevent->timer (
After => 5,
Interval => 2,
CB => SUB {
$count + +;
Warn "This is the first $count call";
if ($count >= 10) {
Undef $w;
}
}
);
$CV->recv;





I/O watchers



Basic syntax





 code as follows:

My $fh = ...; # Open a handle

My $io; $io = Anyevent->io (
FH => $fh, # Open handle above, can also be standard input and output
Poll => "W", # This place can choose R and W to represent read and write IO events
CB => SUB {
Syswrite ($FH, "written content");
Undef $io;
}
);





Use instance:



The following example, using IO monitoring to be able to read, call the CB function, directly read the file Test.txt, one byte at a time, until the file is read through the undef elimination of this event.





code as follows:

#!/usr/bin/perl
Use strict;
Use anyevent;

My $CV = anyevent->condvar;

Open My $fh, "<test.txt" or die "Cannot open file handle $!";
My $io; $io = Anyevent->io (
FH => $fh,
Poll => "R",
CB => SUB {
My $len = Sysread ($fh, my $buf, 1);
if ($len > 0) {
Print "read ' $buf ' \ n";
}
else {
Undef $io;
Die "Read error: $!";
}
});

$CV->recv;





IDLE watchers



Basic syntax





code as follows:

My $w = Anyevent->idle (cb => SUB {...});





Use instance:



The following example runs idle when there are no other events running in the entire program. It is called when other events are waiting and empty.





 code as follows:

#!/usr/bin/perl
Use strict;
Use anyevent;

My $CV = anyevent->condvar;

My $t; $t = Anyevent->timer (
After => 1,
Interval => 1,
CB => SUB {print time (). " \ n "}
);

my $w; $w = Anyevent->idle (
CB => SUB {
Warn "idle";
# undef $w;
}
);

$CV->recv;





SIGNAL watchers



The basic syntax is to run events in callback when a POSIX signal is received.





 code as follows:

My $w = anyevent->signal (signal => "TERM", CB => SUB {...});





Child Procrss Watchers



The basic syntax is as follows





code as follows:

# Child Process Exit
My $w = anyevent->child (PID => $pid, CB => SUB {
My ($pid, $status) = @_;
...
});





Condition variable (multiple conditions)



This is anyevent learn the above several event monitoring must understand. We all see anyevent->condvar; on it. And $CV->recv These two, Condvar is condition variable's shorthand. Refers to when the condition is established when the variable



In fact, it is the condition that exits the event loop when the condition is reached. So there is no loop function in the traditional event in anyevent. So using a conditional variable is equivalent to getting this event to turn.



The basic $CV->recv is a pair of $CV->send, and when the event calls send, there must be recv receive the call before exiting the event.



The following $CV->begin and $CV->end are basically the same. Send is a single condition. Begin and end are multiple conditions when the form exits, in other words, these events are completed in pairs, only to exit the event.





 code as follows:

#!/usr/bin/perl
Use strict;
Use anyevent;

My $CV = Anyevent->condvar (cb => SUB {
Warn "Call end";
});

For my $i (1..10) {
$CV->begin;
my $w; $w = Anyevent->timer (after => $i, CB => SUB {
Warn "finished timer $i";
Undef $w;
$CV->end;
});
}

$CV->recv;





The default Condvar the event with a false variable, so the direct send and begin send, and so on, will become true, and then exit the event loop. It would be nice to see this place as a signal. Y
If the condition is not true, the event will loop throughout the anyevent. So there is no send in the example above.



About Anyevent Other, you can play like Anyevent::http,twiggy after getting started. Look at these applications and projects.



In addition, we often use EV in anyevent. He is a C-Libev Perl interface that has very high performance. Read the above, look at the following EV use, very easy, basically unchanged. Just no conditional variables,
The traditional ev::loop of the use; To make this work.


 code as follows:

Use EV;

# timers

My $w = Ev::timer 2, 0, sub {
Warn "is called after 2s";
};

My $w = Ev::timer 2, 2, sub {
Warn "is called roughly every 2s (repeat = 2)";
};

Undef $w; # Destroy Event Watcher again

My $w = EV::p eriodic 0, 0, sub {
Warn "is called every minute, on the minute, exactly";
};

# IO

My $w = Ev::io *stdin, Ev::read, sub {
My ($w, $revents) = @_; # All callbacks receive the Watcher and event mask
Warn "stdin is readable, entered:", <STDIN>;
};

# Signals

My $w = Ev::signal ' QUIT ', sub {
Warn "Sigquit received\n";
};

# child/pid STATUS CHANGES

My $w = Ev::child 666, 0, sub {
My ($w, $revents) = @_;
My $status = $w->rstatus;
};

# STAT CHANGES
My $w = Ev::stat "/etc/passwd", sub {
My ($w, $revents) = @_;
Warn $w->path, "has changed somehow.\n";
};

# Mainloop
Ev::loop; # Loop until Ev::unloop is called or all watchers stop
Ev::loop Ev::loop_oneshot; # block until at least one event could is handled
Ev::loop Ev::loop_nonblock; # try to handle same events, but don't block





Note: Most of the content in this article comes from the Japanese @lestrrat


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.