Programming in Lua 3 Reading Notes (27th), programminginlua
Date: 2014.8.14Part IV The C API
31 Threads and States Lua actually does not support true multithreading, that is, the preemptive threads shared memory. There are two reasons: First, ansi c does not support this mechanism, so there is no proper method in Lua to implement this mechanism; second, the most important thing is that the author thinks that it is not a good idea to support true multithreading in Lua. Multithreading is a mechanism developed for low-level development languages. The signal, monitoring, and other synchronization mechanisms in the concept of multithreading depend on the operating system rather than applications. Therefore, it is difficult to detect and correct bugs caused by multithreading, some of these bugs may cause security problems. In addition, multithreading may also affect the performance of the program running process due to information synchronization, for example, affecting the program memory allocation. The problems caused by multithreading are mainly caused by the combination of preemptive thread and Memory sharing. Therefore, Lua avoids these problems by using non-preemptive thread and non-shared memory. The Lua thread (also called a collaborative program) is collaborative, so it avoids the problem caused by unpredictable thread switching, and The Lua State does not share the memory, therefore, it provides a good foundation for concurrency. This chapter focuses on these two points.
31.1 Multiple ThreadsThreads in Lua are essentially a collaborative program. We can think that a coprocessor is a thread with a good interface, or we can think that a thread is a coprocessor with a low-level API. From the perspective of c api, it is very useful to think that a thread is a stack. From the implementation process perspective, the thread is indeed a stack. Each stack stores information about all unexecuted calls, parameters of each call, and local variables. In other words, a stack has all the information that a thread needs to run again. Therefore, multithreading means multiple independent stacks. In fact, all the Lua-c api functions we discussed previously are operated on a specific stack. This is known from the very beginning. But how do we know which stack we want to operate? Will the operation be wrong? The key point here is the first parameter type lua_State when we call a function. This parameter represents not only a lua state, but also a thread included in this state. Whenever a Lua state is created, Lua will automatically create a new thread in this state, and then return a lua_State representing this thread. This main thread will never be recycled (this ?? Whether to remove the threads created by calling lua_newthread, that is, the thread automatically created by lua state ). When you use lua_close to close the state, the thread will be released along with the state. You can call lua_newthread in a state to create another thread:
lua_State *lua_newthread(lua_State *L);
The above function returns a lua_State pointer representing the new thread and pushes the new thread into the stack as the thread type, for example:
L1 = lua_newthread(L);
After the above steps, we have two threads, and both threads are actually in the same lua state. Each thread has its own independent stack, and the new thread L1 has an empty stack, while the L thread stores the new thread at the top of its stack. For example:
E. g. printf ("% d \ n", lua_gettop (L1); -- 0 the stack of the new thread is an empty stack printf ("% s \ n", luaL_typename (L, -1); -- thread indicates a thread at the top of the stack, that is, the new thread.Except for the main thread, the other threads are the objects managed by the garbage collection, which is the same as the other objects in Lua. When a new thread is created and pushed to the stack as the thread type, this thread will not be recycled. We should ensure that we do not use threads that are not sure whether they are in the stack. Every call to Lua's API may trigger the collection of threads not in the stack, even if the thread is still in use, such:
lua_State *L1 = lua_newthread(L);lua_pop(L,1); /* L1 is garbage*/lua_pushstring(L1,"helloe"); /* danger */
When lua_pushstring is called, garbage collector may be triggered to recycle L1, even if this thread is still in use. To avoid unexpected errors, always reference the threads in use. for instance in the stack of an anchored thread or in the registry. the newly created thread can be used the same as the main thread. Elements can be pushed and introduced from the stack of the thread, and functions can be called using the stack. Here we introduce a function lua_xmove (L1, L, 1), which is used to move the stack data in the same state, such as lua_xmove (F, T, n ), it is to introduce an element from Stack F and then push it to stack T. In this operation, we do not even need to create additional threads, but only need to process them in the main thread. The premise of using multithreading here is to implement a collaborative program so that we can delay or resume the execution of a thread. To resume execution of a function, you need to use the function lua_resume to support: int lua_resume (lua_State * L, lua_State * from, int nary). This is the case if we use lua_pcall, if we want to run a collaborative program, we can use the lua_resume function: the function to be called, the parameter is pushed to the stack, and the function parameter narg represents the number of parameters passed. (The from parameter refers to the state of the thread that executes the call ). The main behavior is similar to lua_pcall, but there are three differences: 1. lua_resume does not represent the number of returned values, and the function always returns all returned results; 2. If no parameter is provided for the message handle, the error will not be triggered in the stack. Therefore, you can check the stack after the error (~~~ 3. If the program is suspended, lua_resume returns a special code: LUA_YIELD, and leaves the thread in the state for future calls. The coprocessor can also call C functions, which can also call back other Lua functions.
31.2 Lua StateEach time you call the luaL_newstate function, a new lua state will be created. different Lua states are independent of each other, which means that the events in a state do not affect other States, and that data interaction cannot be performed directly between States, instead, C code is required. For example, lua_pushstring (L2, lua_tostring (L1,-1); the above Code transfers the elements at the top of the L1 stack to L2 using the c api. Because we need to use c api to implement data interaction, the Data Type passed must be the type supported by C, data such as table needs to be converted in an appropriate way before it can be transmitted. In a system that supports multiple threads, it is worth exploring to create an independent Lua state structure for each thread. The result of this structure is similar to processes in UNIX. Here we can get concurrency without sharing memory. The rest of this section is the introduction of using POSIX Threads to create independent Lua States for each thread mentioned above. It is a bit difficult to understand and no longer takes notes. I will try to understand it later.
Reading Notes "XXXXXXX" 1 Excerpt () 2 reading (Key Sentences) 3 understanding (full-film inspiration) 5 articles must follow the instructions
One thousand and one night reading notes
"One Thousand and One Nights" is a classic Arabic literature that is well-known to all people in the world. The large dance drama "One Thousand and One Nights" tells the audience the story of the birth of this masterpiece, which is well known all over the world: in ancient times, king shannuya of the sassan Kingdom hated a woman for his wife betrayed him. Therefore, he kills a woman every night after the night. Three years later, the daughter of Prime Minister went to the palace and told the King a story every night. She stopped at dawn and went on to talk about it the next day. After 1001 nights, the king finally dismissed the idea of killing a woman, and the world famous "One Thousand and One Nights" was born. "One Thousand and One Nights" is a book that I like very much. "One Thousand and One Nights" is also called "Arabian Nights". There are many strange stories in "One Thousand and One Nights, there are the stories of shanluar and shanluzuode, the stories of fishermen and demons, the stories of fishermen and four-color FISH, the stories of Prince touching, and the pictures of Bai houtu. stories, etc, there are humorous, sad, interesting, terrible, and miserable stories here. I think there are good or bad stories in One Thousand and One Nights, for example, the adventure of fisherman Zhu del is not good. Zhu del is happy by strength and luck, but Aladdin lamp is a good one, because Aladdin relies on a heart that is not discouraged and brave to win happiness. The story of Sarah "One Thousand and One Nights" should start from Arabia. In the story, the heroine Sarah has a special liking for folk songs and exotic scenery from different countries. Just like the enthusiastic desert in the Middle East, Sarah also spread her passionate songs to the Quartet. for Sarah, a good story must be shared by an audience, with a unique idea and unparalleled singing voice, Sarah, who came from "One Thousand and One Nights", will bring her story to Shanghai, China, let's see how the goddess of moonlight continued to write this beautiful myth.
Read the book notes of "never stop weapons"
A person who has said goodbye to weapons is either a prisoner of the enemy or a prisoner of love. I am not very good at self-protection. I am really a person who gives up self-protection. just like the database of life, you can open all programs and read all files at any time without entering the password. what I am talking about is a prisoner in this sense. when I put myself in the sun, I realized that there was no disguise, and the days of concealment were disturbing. when I realized that the resistance was helpless, how much time was irretrievable, and how much memory gradually fades out from my heart. after all, a prisoner is a person who cannot resist harm, that is, to have enough courage to give up hope and must bear all the pressure to survive. originally, in a personal space, you can immerse yourself in your own fantasies, and you can create virtual flowers from the dust. a person who gives up self-protection cannot cheat himself, only by constantly purifying the inner world.
Reading Notes in hampto
Shakespeare's "Hamlet" is a classic masterpiece. on the surface, this book is not much different from historical legends. It tells the story of Prince Denmark's revenge for his father, which is full of bloody violence and death. as
Horazu, a Chinese character in the drama, said: you can hear rape and kill, unusual repairs, decisions in the dark, accidental slaughter, tactics of killing by hand, and self-harm ending. the twists and turns of the plot, closely around revenge
Expand. he hurried back to China from wandunburg, Germany to attend his father's funeral. What makes him unacceptable was that he did not catch up with his father's funeral, he witnessed the wedding of his mother and uncle kraudis, which had made hamwright suspect. In addition, at night, he met his father's dead soul on the terrace of the palace Castle and mourned, this violent behavior was done by Uncle James and asked him to avenge his father. so far, he began a difficult revenge process, and began a battle with kradis. in the end, the sword of revenge was issued to kradiss.
Count of Christchurch Reading Notes
Love is complete, hate is thorough. the reward is complete, and the revenge is complete. this is what I feel most after reading "Revenge of Christchurch. there is a saying in China that revenge of a gentleman is not too late for ten years. Revenge also needs to be refined and powerful, and it is not just a matter of time. the Count of Christchurch explained the saying most specifically with his own actions. after 14 years of his career in the dungeon, his life is to find his loved ones, beneents, and enemies. after confirming the person we are looking for, he does not see what we have seen in martial arts novels ...... remaining full text>
10 Reading Notes
Childhood Gorky
Excerpt from good words:
Suddenly as it comes, erratic, interesting, and shining
Excerpt from a good sentence:
On the blue water of the Volga River, orange ships are flowing against the current, and a piece of golden leaves are drifting slowly.
I am very afraid of my grandfather. I always think that his green eyes are always staring at me.
The song was filled with sorrow, as if it was the river flowing down the mountains, stirring in the room.
Some people often hear their songs and stop and look at them from the bottom of the window. The raised face reminds me of the dirty dishes that were not washed.
Excerpt from the good section:
"Alas, you guys ......!" He often suddenly sighs, and does not know what to sigh. "People ......" The ending sound is always pulled long by him.
Ioka's face turned red to the middle of the kitchen, beating like a flame: the two hands raised high, fast and difficult to distinguish, the shirt jitters, like the burning of the general brilliant. He danced with indulgence, as if he had opened the door and let him go out, he could dance all over the city! Everyone was infected by him and then trembled with him.
In singing, the grandmother sometimes advances, sometimes moves back, sometimes flies, and the Youth instantly returns to her body, so that she presents a beautiful flower. Everyone is attracted by her.
My thoughts:
The author wrote the dirty environment where the hero was at that time, and made great efforts in language description. Make the article vivid and immersive, and have a deeper understanding of the beauty and ugliness and the complex feelings of people.
Good words and good sentences in Robinson ripple
Excerpt from good words:
Stranded, full-disclosure, swallowed up, smoke filled, swimming, shanao, gongshun, stunned, spotted marks
Excerpt from a good sentence:
I was so scared that it was like a blue ray.
I was furious when I saw this scene. I swear in my heart: I will never let them go if I see this type of violence again next time!
Excerpt from the good section:
There are a lot of melons on the ground, and the trees are full of a bunch of grapes. There are plenty of yellow lemons. I looked down the slope of the orchard, and there was a fresh and green landscape everywhere. This was full of joy in my heart, and I suddenly felt like an indisputable master of this rich land.
1. When we start to do one thing, if we don't calculate the cost in advance, or make a correct estimation of our own strength in advance, it's really silly.
Thoughts on reading Robinson drifting
This article focuses on the story of Robinson overcoming many difficulties through his own work on the desert island, finally defeating the harsh environment, returning to his hometown on Friday with the indigenous people and having a happy life.
What I admire most is not Robinson's diligence and courage, but his amazing psychological endurance. It can be imagined that a single living person has lived on a desert island for more than ten years, and no one has accompanied him, or even the most basic, and cannot simply talk to a person for a while. The whole deserted island has no houses, no rice fields, and he can only work hard to create a world.
7-insects-saving expert Walker by Faber
Beautiful words
Proud, disdainful, respectful, arrogant, offensive, fleeing, proud, bitter, Lucky, afraid, fulfilling, talking to yourself, tricks, deterrence, absurd, weinonuo, noisy, without a comment timid, come forward, unafraid, fainting, fire, in a variety of ways, stupid, mean, abuse, creepy, exhausted, unconscious, curled up, pity, angry, unbearable, scrambling for fear
Wonderful Period
We don't know what death is, so we won't pretend to be dead! No matter what kind of abuse we suffer, we are always upright insects and will never cheat others.
Don't say it's because we can't fly! Don't say it's because we are not running fast! We do not know what death is, so we will not pretend to be dead!
Especially suicide. I never even thought about it! Only mean people will do that stupid thing!
Feelings after reading
The strong will also occasionally avoid competitors that are more powerful than themselves, so as not to lose their own lives. The author has a thorough understanding of the arms. It is a self-defense method when the beetle fails to defend against each other, in this world, whether it's human beings or other animals, as described in this book ...... remaining full text>