You are reading the article How Does Mutex Work In Go Language With Examples? updated in December 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How Does Mutex Work In Go Language With Examples?
Introduction to Golang MutexWeb development, programming languages, Software testing & others
Syntax of Golang MutexIn the below syntax we can see the locking and unlocking of the operation.
First we lock with the help of the mutex, remember to use the mutex we need to import the package called sync, and on sync we can call the mutex locking.
Here locking means it will not take any other call till it will not complete the current call.
Second we are performing the operation, you can take any operation like addition or calculation of the amount from your current account also.
Once the activity for which the code block is there will be done the unlock will be called.
Unlock will remove the locking which we applied on the code block and again another call be taken.
Remember we use this only for locking to any very critical type of the code block and that code block is not needed to run in the concurrent (Here concurrent means the call should be made only for the code which can not run for multiple time for an user or related one specific attribute ).
Given below is the syntax:
mutex.Lock() y = y - number mutex.Unlock() How does Mutex work in Go Language?You must have withdraw money from ATM many times suppose in your account there is 5000 rupees and you are doing ATM transaction as well as you are paying to some other shop also by using online medium of transaction in that case it can be possible that in ATM you have withdraw amount 5000 and 5000 you are trying to pay to your shop by online, now how to control this because if we will not control this than both the transaction can be done if both happens at the same time. Hence it will be a loss for the banks, so to avoid this kind of situations we use the concept of mutex which allow us for locking of particular code block. Here such case it will lock the code block for once it will find any transaction and will not allow other transaction till previous transaction which started will not complete.
Given below is the working of Mutex:
Mutex is the part of the sync, so to use the mutex we need to import the sync package of the go language.
Once we use the mutex.lock() whatever the code lock next to it will be there it will block that code till the execution of the code block will not complete.
Code blocks can be anything like calculation of any arithmetic calculation or calculation of the payment transactions.
Finally the process of unlocking mutex.unlock so once the unlocking get call means the code has completed and next execution for the code block can be allowed.
Examples of Golang MutexGiven below are the examples mentioned:
Example #1In this example we can see the race conditions which means code block is not getting locked and it will be called simultaneously and hence before completion of the previous call it will make another call and hence it will go into the race conditions.
Code:
package main import ( "fmt" "sync" ) var UPT = 0 func worker(st *sync.WaitGroup) { UPT = UPT + 1 st.Done() } func main() { var s sync.WaitGroup for i := 0; i < 1000; i++ { s.Add(1) go worker(&s) } s.Wait() fmt.Println("The y value is", UPT) }Output:
Example #2Code:
package main import ( "fmt" "sync" ) var UTV = 0 func worker(wt *sync.WaitGroup, k *sync.Mutex) { k.Lock() UTV = UTV + 1 k.Unlock() wt.Done() } func main() { var s sync.WaitGroup var n sync.Mutex for i := 0; i < 1001; i++ { s.Add(1) go worker(&s, &n) } s.Wait() fmt.Println("The y value is", UTV) }Output:
ConclusionFrom this article we saw the basic concept of the mutex in the go language, we saw the working of the mutex and we also saw about the syntax of the mutex. We focused on the some of the important examples of the mutex which can be used for real world.
Recommended ArticlesThis is a guide to Golang Mutex. Here we discuss the introduction, syntax, and working of mutex in go language along with programming examples. You may also have a look at the following articles to learn more –
You're reading How Does Mutex Work In Go Language With Examples?
How Does Rune Work In Go Language?
Introduction to Golang Rune
Web development, programming languages, Software testing & others
SyntaxBelow is a simple syntax for the where we show how we can create a run, so basically it is simply assigning the characters or punctuation to the run variable. We can explain the below syntax in the following steps .
First, we have taken a variable run, here you can give any name to this variable and assign them values.
Next, we get the Unicode of the run variable. Simply with the command reflect.Type(run).
Remember the reflect is the package which we need to import to see the Unicode value of the run, or of the characters.
Please see the below syntax for understanding.
run := symbol of punctuation reflect.TypeOf(run) How Does Rune Work in Go language?So before understanding the working of the runs we need to understand why it is being introduced, actually there are many languages and punctuation’s so it plays a role of the intermediate which allow many languages to work and a unique code for every language so that it will be easily understandable in a common way for all other languages. We can discuss the working of the runs in the following steps.
When we write any string with more than one character it will not work with that, as it is made for single characters.
We can see an example of UTF-8 which encodes the all Unicode for 1 to 4 bytes and here out of the 4 bytes 1 byte will be used for the ASCII characters and remaining will be used for the runs.
We should be aware that every ASCII contains a total of 256 attributes. Out of these 256 characters, 128 characters are the numbers from 0-127 these are reserved for them.
We do not have to do anything to perform the runs it manages internally, which Unicode generation is there internally, if anyone wishes to see the Unicode for any characters they can see by using reflect package of the go language. Now to use the reflect package of the go language we need to import the reflect.
We will see that out of the reflect package that every character has a unique value and that unique value is Unicode, this code will be the same for all the languages so that everyone can use them without hesitation and thinking as an issue for the other people to use this in their languages.
Once we assign some value of character or punctuation to any variable there will be a Unicode for that will also be there and that uncode will be similar for other environments which gives flexibility.
Examples to Implement Golang RuneIn the below, we have given some of the examples for the string and numeric and symbols type characters and we were tried to print the value of them. In case if we want to execute these examples then we can create a file with the name of chúng tôi and copy and paste the examples of the below codes and run the command go run chúng tôi We can even create file any name according to our requirements.
Example #1Below is an example where we are working with the runs generated with the character and we are printing the output of every character and their Unicode also. We are also printing the type of character.
Code:
package main import ( "fmt" "reflect" ) func main() { code1 := 'B' code2 := 'g' code3 :='a' fmt.Printf("The actual code is : %c; The Unicode is: %U; Type: %s", code1, code1, reflect.TypeOf(code1)) fmt.Printf("nThe actual code is : %c; The Unicode is: %U; Type: %s", code2, code2, reflect.TypeOf(code2)) fmt.Printf("nThe actual code is : The Unicode is: %U; Type: %s", code3, reflect.TypeOf(code3)) } Example #2Below is an example where we are working with the runs generated with the numeric and we are printing the output of every numeric value and their Unicode also. We are also printing the type of numeric.
Code:
package main import ( "fmt" "reflect" ) func main() { r1:= '1' r2:= '2' r3:='3' fmt.Printf("The actual code is : %c; The Unicode is: %U; Type: %s", r1, r1, reflect.TypeOf(r1)) fmt.Printf("nThe actual code is : %c; The Unicode is: %U; Type: %s", r2, r2, reflect.TypeOf(r2)) fmt.Printf("nThe actual code is : The Unicode is: %U; Type: %s", r3, reflect.TypeOf(r3)) }Output:
Example #3Code:
package main import ( "fmt" "reflect" ) func main() { r1:= '*' r2:= '#' r3:='&' fmt.Printf("The actual code is : %c; The Unicode is: %U; Type: %s", r1, r1, reflect.TypeOf(r1)) fmt.Printf("nThe actual code is : %c; The Unicode is: %U; Type: %s", r2, r2, reflect.TypeOf(r2)) fmt.Printf("nThe actual code is : The Unicode is: %U; Type: %s", r3, reflect.TypeOf(r3)) }Output:
ConclusionFrom this tutorial, we learned the basic concept of the runs in the go language and we learned the working and its syntax. We also focus on some of its examples for understanding the runs for the character’s number and for the symbols.
Recommended ArticleThis is a guide to Golang Rune. Here we discuss the basic concept of the Golang Rune and its syntax along with the help of some useful examples and Code Implementation. You can also go through our other suggested articles to learn more –
How Does Javascript Grid Work And Examples
Introduction to JavaScript Grid
Web development, programming languages, Software testing & others
Syntax:
The JavaScript grid layout have some more different syntax for each screens on the web page based on the user requirement it may vary.
—javascript functions and logic codes—
The above code is one of the basic syntax for grid layout columns and rows used in the html with JavaScript functions.
How does JavaScript Grid work?When we have a grid layout in the web page it will work with the different functionality based on the customized views. The grid contains rows and columns for each multiple columns. They have separate layouts in generally is not acceptable for mobile devices because mobile screen have narrow screen widths but some times we may have need to place or enter the small values with side by side in the web page applications in mobile views it may vary upon the mobile screens but the scenario is we have place the values like using navigation or buttons or some other ui tag elements.
The grid layout is not only used for JavaScript it is used for some other JavaScript libraries like jquery, Angular frameworks etc. In JavaScript Masonry is one of the JavaScript grid layout library we can access all the datas and display with the table format using this library grid is an intersect and set of horizontal and vertical lines one is set for defining columns and the other lines contains rows elements and values are placed onto the grid within these rows and columns lines for each layout. We can also use the grid tracks for rows and columns on our grid with the grid-template-rows and grid-template-columns properties these are called and defined as grid tracks. A grid track is one of the concept for space between the two lines on the grid.
The JavaScript grid system with multiple ways to layout the html contents with equal width, specific width, dynamic and self adjusting rows and columns. We can use Plain JS API for used everywhere in the web pages. If we use system with some multiple ways for horizontally aligned contents and push to start, middle and end or justify around/in-between Plain JS api for used every where in the horizontal grid layout. We can use another type of grid layouts called Offsetting columns. Grid layout will used for pushing content with column offsets adjusted with the left margin with as much as needed for offsetting columns plain jsapi for used everywhere in the offsetting columns in JavaScript grid layouts.
ExamplesGiven below are the examples mentioned:
Example #1Code:
*{ box-sizing: border-box; } body{ font-family: Times New Roman; } .first { background: green; max-width: 203px; } .second{ content: ”; display: block; clear: both; } .third { width: 161px; height: 122px; float: right; background: red; border: 3px solid #444; border-color: hsla(0, 1%, 2%, 0.3s); border-radius: 3px; } .fourth { width: 323px; } .fifth{ width: 483px; } .sixth{ width: 6450px; } .seven { height: 202px; } .eight{ height: 263px; } .nine { height: 364px; } $(‘.first’).masonry({ itemSelector: ‘.third’, columnWidth: 163 });
Output:
Example #2Code:
Output:
Example #3Code:
var b = document.getElementsByTagName(“welcome”)[0]; var o = document.createElement(“my”); var k = document.createElement(“domains”); for (var i = 0; i< 2; i++) { var r = document.createElement(“tablerow”); for (var j = 0; j < 2; j++) { var c = document.createElement(“tabledata”); var text = document.createTextNode(“row cells “+i+”, column cellss “+j); c.appendChild(text); r.appendChild(c); } k.appendChild(r); } o.appendChild(k); b.appendChild(o); o.setAttribute(“cells border”, “3”); functiondemo() { m = document.getElementsByTagName(“body”)[0]; n = m.getElementsByTagName(“tables”); p = n[1]; p.style.border = “12px”; }
Output:
ConclusionThe JavaScript application we have used so many features and libraries in the web pages like tables, grid layouts etc. It is used to show how to integrate the application with grid layouts and tables in easy manner and also we configured the JavaScript with grid techniques libraries.
Recommended ArticlesThis is a guide to JavaScript Grid. Here we discuss how does JavaScript grid work? and examples respectively. You may also have a look at the following articles to learn more –
How Exist Function Work In Matlab With Examples?
Introduction to Matlab exist
In Matlab, the ‘exist’ stands for existence. ‘exist’ function checks the existence of variables, functions, classes, folders, etc. this function helps us to know about the available checklist in the Matlab workspace. If the given file or folder is already present in Matlab, it will create an error while creating a new file with the same name and use the same folder instead of the new folder so that space will be optimized. This function gives integer values as output; This output return value varies from 0 to 8.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
Syntax
exist input
exist (‘max’)
exist (‘inbuilt function name’)
exist gui file
exist Matlab file name file
exist until dir
exist folder name dir
How exist function work in Matlab?‘Exist’ function returns values in the form of integers. If a given quantity is present in Matlab, then it gives an output from 1 to 8 depending upon the type of quantity. And if the given quantity is not present in Matlab, then it gives the output as ‘0’. We can check the existence of variables, files with extension ‘.m’, ‘.mlx’, ‘.mlapp’, ‘.mat’, ‘.fig’,’.txt’ ), folders as dir, inbuilt functions, classes, etc. if the given variable is present in Matlab workspace then it returns number ‘1’, for files it returns ‘2’ or ‘3’. If it is a simulation model, then it returns chúng tôi we are checking the existence of the inbuilt function, then it will show presence by ‘5’, and for folders, it will return ‘7’.
ExamplesHere are the following examples mention below
Example #1 ( Variables )In this example, first, we need to create one variable, then we can check the existence of the variable; here, one variable is created, which is ‘input ‘. After variable creation, we have used the existing function on the variable; therefore, the output is 1 that means the ‘input’ variable is present in Matlab workspace, which is illustrated in example 1(a). in example 1(b), without creating any variable, we directly applied the function on the ‘output’ variable, and it returns the result as 0, which means the ‘output ‘ variable is not present in the Matlab workspace.
Matlab code for Example 1(a) –
exist input
Output:
Matlab code for Example 1( b ):
exist output
Example #2In this example, we will check the existence of inbuilt functions from Matlab. There are various functions available in Matlab like max, mean, min, avg, import, disp, use, and so on. Here we have used the max’ function to check existence obviously as we know it is present in Matlab so that it will return output value as ‘5’. And we will use one random name, ‘abc’, it will return output as ‘0’, which means there no such function available in Matlab, which is illustrated in example 2.
Matlab code for Example 2:
exist(‘abc’)
Output:
Example #3This example will check the existence of files in Matlab. To check the present first, we need to create one file, here we have created a Matlab file with the name ‘gui.m’. There is a limitation on extensions to check the existence of files; only a few extensions are allowed like ‘.m’, ‘.mlx’, ‘.mlapp’, ‘.mat’, ‘.fig’,’.txt’. As we have already created a Matlab file with extension .m, then we will get the output as ‘2’. Numbers ‘2’ represent the existence of files. On another side, we have checked the existence of file gui10; it returns the value 0, which means there is no such file with the name gui 10 in the workspace.
Matlab code for Example 3:
Output:
Example #4In this example, we will check the existence of a folder. To check existence in the directory, first, we need to create one folder, here we have created one folder in the directory ‘util’, and after checking existence, it returns the value ‘7’. That means the given folder is present in the directory, and the number ‘7’ represents the folder’s existence in the Matlab workspace. Then we checked the existence of another folder, ‘util10’, which is not present in the directory so that it will return the result as ‘0’.
Matlab code for Example 4:
exist util10 dir
Output:
ConclusionIn this article, we have seen various uses of the ‘exist’ function. It checks the existence of almost every factor which is required in stands implementation of any model. There is some alternative to existing a function like ‘is file’ and ‘is the folder’, but instead of using different syntax for each term (variable, files, folders, function, class), it’s good practice to use the same function for all the terms.
Recommended ArticlesThis is a guide to Matlab exist. Here we discuss How to exist function work in Matlab and Examples along with the codes and outputs. You may also look at the following articles to learn more –
How Does Umask Work In Linux With Syntax?
Introduction to Linux Umask
UMASK is an abbreviation for user mask and is sometimes called a User file creation mask. In Linux, there are many instances when one would need to create a file or a directory as per the use case requirement. While doing this, one needs to make sure that the permission of the newly created file or directory should comply with the use case scenarios. Now, suppose a Linux system is used for developing applications suited for only one kind of scenario tackling. In that case, it is erstwhile to change the base permission or the default permission of the newly created files or folders. UMASK is the command that comes in handy while fixing the default permission to something that most applications being developed in that Linux box would typically have.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
SyntaxBefore we even jump into understanding what scenarios umask would help or what is the working principle of umask, it is beneficial to understand the syntax behind the umask so that while going through the working principle, we can keep the syntax in mind.
Syntax #10: read-write and execute
1: read & write
2: read & execute
3: read-only
4: write & execute
5: write only
6: execute only
7: no permission
If you recall from a previous understanding of file permission, you would see that the numbers are just the opposite of the actual file permission numbers. The reason is the calculation we will talk about. Using the numbers in the umask, you would see that the permission to the file or directory is the one you would be expecting as text and not the numbers listed above. So, for example, after calculation, if umask is 1st number is 0, you would get 7 or 6 as the 1st number post calculation, and that is exactly the number for reading, write and execute for a file or directory, respectively.
Syntax #2 umask u=rwx, g=, o=Here umask is the same keyword, u refers to users, g refers to groups,o refers to others. And the letters r refers to read,w refers to write,x refers to execute. Here as well, there is a calculation that will follow to get to the actual file permission.
How Does Umask Work in Linux?In order to understand how umask works in Linux, it is more important to note a few important parameters that become the base for obtaining the file permissions. By default, base permission for a file is 666, and the directory is 777. Number 7 won’t exist, and number 6 will have action as No permission in case of files. This is because it is a rule of thumb that files with execute permissions are not allowed to be created by Linux, and one would need to do that after the file is created and as a separate step!
The next thing is how and where do we change the value of umask. This needs to be changed in the ~/.bashrc file. ~/.bashrc lets you set parameters or attributes or configurations for terminal sessions. In case you need to change the umask for only current sessions, you would need to put it as a command-line input.
umask 027 umaskOutput:
Once you have set the umask values, these will try to be used as a NOT operator to calculate the file permissions. As already mentioned, the default base permission for files is 666. The directory is 777; let us look at 2 different calculations (for files and directory) to understand how we arrive at permission numbers from the umask code.
Get File permissionThe intention is to subtract the umask number from the base permission to get the actual file permission. For example, if the umask is 027 [0 (read & write for user), 2 (read-only for the group), 7 (no permission for others)] then the calculation is as follows:
Base permission: 666
umask: 027
File permission: 666 – 027 = 640* (rw-r—–)
*Please note that 6 – 7 is -1, but in Linux, it is adjusted to be 0.
Get Directory PermissionThe intention is to subtract the umask number from the base permission to get the actual file permission. For example, if the umask is 022 [0 (read, write& execute for user), 2 (read & execute for group and others)] then the calculation is as follows:
Base permission: 777
umask: 027
File permission: 777 – 022 = 750 (rwxr-x—)
Groups can read and execute into a directory but can only read a file inside it.
Others can do nothing, i.e., no permission.
Without umaskCode:
mkdir new DirWO touch new FileWO ls -lOutput:
With umaskCode:
umask 027 mkdir newDir touch new File ls -lOutput:
A useful tip: Try to first understand the base scenario and then watch out for permission in a numerical form. Then subtract it from the base permission to get the umask number.
ConclusionIn this article, we have learned about how we use scenario-based numbering to understand what the default umask number should be, and then in accordance with that, we set up the umask either in bashrc or only for that terminal only as per requirement.
Recommended ArticlesWe hope that this EDUCBA information on “Linux Umask” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Does Pseudocode Algorithm Work?
Introduction to Pseudocode Algorithm
Pseudocode algorithm is used while programming or is associated with writing algorithms. Pseudocode is a method that helps the programmer to define an algorithm’s implementation. We can also say that pseudocode is a cooked-up representation of a basic algorithm. In pseudocode algorithms, the algorithms are represented using pseudo codes as it is easier for anyone to interpret the pseudo-codes even if they do not have any programming background or are used to a different programming language. As the name explains itself, pseudo-codes is a false code that can be understood by a layman with a basic knowledge of programming.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
How does Pseudocode Algorithm Work?Writing an algorithm using pseudocodes is quite similar to writing in a coding language. Writing an algorithm is done on its own line in sequence. Generally, uppercase is used for writing the instructions and lowercase is used for writing the variables and the messages are written is sentence case. In pseudocode, the question is asked in INPUT and the message is printed by the OUTPUT.
Examples of Pseudocode AlgorithmFollowing are the examples as given below:
Example #1In this example, we will check if the user has age below 50 years or more.
Step 1
Put the input value
The input is stored in the respective variable ‘age’
INPUT user inputs their age
STORE the user’s input in the age variable
Step 2
OUTPUT ‘My age is less than 50’
ELSE
OUTPUT ‘My age greater than 50’
OUTPUT ‘My age is:’ age
Actual Code:
print(“My age is :”, Age)
Output:
Example #2Step 1
Put the input value
The input is stored in the respective variable ‘age’
INPUT user inputs their age
STORE the user’s input in the age variable
Step 2
Code:
OUTPUT ‘My age is:’ age
Code:
print(“My age is :”, Age)
Output:
Example #3Step 1
Put the input value of Rahul’s age
The input is stored in the respective variable ‘Rahul’
INPUT user inputs their Rahul’s age
STORE the user’s input in the Rahul variable
Step 2
IF rahul< 50 THEN
OUTPUT ‘Rahul age is less than 50’
ELSE
OUTPUT ‘Rahul age greater than 50’
OUTPUT ‘Rahul age is:’ Rahul
Put the input value of Ankush’s age
The input is stored in the respective variable ‘Ankush’
INPUT user inputs their Ankush’s age
STORE the user’s input in the ankushvariable
Step 4
IF ankush<50 THEN
OUTPUT ‘Ankush age is less than 50’
ELSE
OUTPUT ‘Ankush age greater than 50’
OUTPUT ‘Ankush age is:’ Ankush
Step 5
Another condition is used here, where the values under the variables ‘Rahul’ and ‘Ankush’. If the condition fulfils then print the output statement otherwise print the else statement.
OUTPUT ‘Rahul is elder than Ankush’
ELSE
OUTPUT ‘Ankush is elder than Rahul’
Actual Code:
end
Output:
Example #4Step 1
Put the input value of age
The input is stored in the respective variable ‘age’
INPUT user inputs their age
OUTPUT ‘Actually I am:’ age
Step 2
IF age == 60 THEN
OUTPUT ‘Got to know that, your age is 60’
Step 3
IF age==5 THEN
OUTPUT ‘Got to know that, your age is 5’
Step 4
ELSEIF age==0 THEN
OUTPUT ‘Got to know that, you are not born :P’
ELSE
OUTPUT ‘Sorry! I guess we are unable to determine your age’
OUTPUT ‘Told you man! my age is:’ age
Actual Code:
print(“Told you man! my age is: “, Age )
Output:
Advantages
Pseudo codes help the codes to majorly focus on the logic which is to be used in the program rather than the syntax of the programming language.
Pseudo codes are independent of any programming language which makes it easier to translate it into various languages.
The coders are given the liberty to express their logic in plain English language without any restraints of major syntaxes.
Writing actual codes become easier for the coder if they use pseudo-codes for writing the algorithm initially. As basic algorithms are not so concise and pseudo codes make the algorithm concise enough to make it more readable and easier for modification.
If we compare flow charts to pseudo-codes, flow charts are lengthier to write and difficult to represent. On the other hand, pseudo-codes are easier to write and programs can be easily translated. The coders just have to focus on the meaning underlined. The major line of focus is to solve the problem with logic rather than being stuck at using the language perfectly.
Using pseudo-code words and phrases while writing an algorithm eases the process of translation of algos into actual programming codes.
Conclusion Recommended ArticlesThis is a guide to Pseudocode Algorithm. Here we also discuss the definition and how the pseudocode algorithm works along with different examples and its code implementation. You may also have a look at the following articles to learn more –
Update the detailed information about How Does Mutex Work In Go Language With Examples? on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!