Trending March 2024 # How To Work With File In Lua With Example? # Suggested April 2024 # Top 4 Popular

You are reading the article How To Work With File In Lua With Example? updated in March 2024 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 April 2024 How To Work With File In Lua With Example?

Definition of Lua File

File is used to store data, read data, and so on like other programming languages. In Lua, we have a different library that can handle files in Lua. Lua support the various built-in library by the help of which we can handle our file in Lua programming, we can open, close or read from a file by using this library. File I/O library is the most common one to use in Lua. By the use of this, we can export and import the data from a large file into our programming, I/O library provides us several features by which we can handle our files in Lua efficiently. In the coming section, we will discuss more file in Lua in detail and how to use and implement this while programming.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

io.open([Your_file_name] [, [your_mode]])

As you can see in the above lines of syntax, this is the basic syntax to open a file using IO in Lua. Inside this, we are mentioning the filename followed by the mode in which we want our file to be handled. let’s take a practice syntax for beginners to understand it in a better way see below;

e.g. :

io.open( "demo.lua" , "r"] ) How Lua file works?

As we already discussed file is used to store a large amount of data, by the use of a file we can export and import a large amount of data from the file. It is very easy to read large data from the file. In Lua file Io works in the same way like C programming language, it divides it into two basic modes which is as follows;

1) simple mode: Simple mode in Lua deals with the current input and output files. It also provides us some operations which is related to these files only.

2) complete mode: this is also known as Full mode, it uses an external handle to achieve this.

Now we will take look at all the operations that can we perform by using this IO library in Lua see below;

1) Open a file: To open a file we can use io. open() function which takes two parameters as the input param, one is the file name another mode is the mode for the file. In the coming section of the tutorial, we will discuss more the modes of file in detail.

2) to close a file: We can also close an existing file if we do not want to perform any further operation on it. For this IO library provide us io.close() function.

e.g.:

io.close(file_name)

As you can see in the above lines of syntax we can pass the file name inside the close() function so it will close the respective file for us.

3) write to a file: If you want to write to an existing file then we have write() function available for this. Below see the syntax for better understanding;

e.g. :

io.write("Your string")

As you can see in the above lines of code we are passing our string inside the write() function, this will add this string at the end of the file.

4) To read file: Io library also provides our function by the help of which we can read the file content. It provides us read() function for this, we can call this function o IO object. let’s take look at its syntax how it looks;

e.g. :

io.read();

Now we will discuss different modes of file in detail see below;

1) “r”: This is the default mode of the file, it enables the ready only mode.

2) “a”: This stands for append mode, to will open the existing file or it will create a new file for us.

3) “w”: This stands for write mode in IO library, it will either create a new file or override the existing one.

4) “r+”: This represents read and write both modes for a file.

5) “a+”: This represents read and append mode on the file. it will either create a new file or it will open the existing one for us.

6) “*a”: This mode will help us to get the content of the file but from the current position of the file.

7) “*l”: This also helps us to read the file from the current position, after reading it will move the position to the next line of the file.

We have some methods available by the Io library which are as follows;

e.g. :

io.type(your_file)

2) io.flush(): As it, the name suggests it will clear out the default buffer.

e.g. :

io.flush()

3) io.tmpfile(): As its name suggests it will return us the temporary file. On this file, we can perform two operations that is read and write, once we close or quit the program this file will be removed.

4) io.lines(): This provides us the iterator which will iterator through the complete file.

Example

In this example we are trying to create a file with mode “w”, we are reading and writing to the file and printing the file content using read() function from IO library of Lua. This is a sample example for beginners to understand it better and implement this while programming in Lua.

Code:

print("Demo to show file IO functionality in lua !!") myfile = io.open("demo.lua", "w") io.input(myfile) myfile = io.open("demo.lua", "r") print("File created success fully !!") print("print the content of file ::") print(io.read()) print("writing to the file ::") io.write("This is sample program to show file in lua !!") print(io.read()) io.close(myfile)

Output:

Conclusion

To handle file in any programming language we would require a library which will help us to read, write, close, etc to perform operations on the file. In Lua we have IO library for this, which provide us some methods and mode to handle the file, it is an inbuilt library in Lua which works in the same way like C language.

Recommended Articles

We hope that this EDUCBA information on “Lua File” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How To Work With File In Lua With Example?

How To Implementgrid View With Example

Introduction to chúng tôi Grid View

Grid view is one of the very popular views in the current IT industry. This is one of the very common expectations currently by every client for presenting their screen specifically in Grid view. It is basically a table presentation based on the values that came from one data source. It can able to control that specific data source and display in the screen as per the requirement of the client, mainly each column considering as a field in the data source and each row considering as a record of that specific column. This control has various features for multiple types of presentation on the screen, we will cover it in this document in detail.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of chúng tôi GridView

ASP.net Gridview is one of the very popular implementations for the specific applications in the current scenario. Grid view mainly handles data sources, controlling the same, display it on the screen as a table. Here every column is mainly representing as a field, and each row in the data source represents a specific record of that corresponding column.

There have multiple features supports by this Grid view, explaining below:

SQLDataSource: Mainly require to maintain binding. Passing data source have huge data which mainly relate to specific fields in the screen. This control helps for binding those fields with data source available data.

Sorting: It has the ability to sorting the data. This Grid view presentation default gives one sorting utility, don’t need to write any additional code for that. Representing data can be sort as ascending or descending order based on the link provided in the screen.

Updating & Deleting: Can update or delete any data from the screen or data source. This ability ensures easy handle of the data from the screen by the end-user. This facility can be given based on some chosen parameters of the grid view presentation.

Pagination: This is also very much requiring features of any of the views presented in the current industry. When huge data came into the data source and Grid view unable to present entire data on the screen, it can default break it with multiple pages and giving this pagination utility to the end-user. It also has searching utility with any text, which helps the user to find out specific data easily.

Row selection: This is also one of the key utilities. Grid view gives the option to end-user for selecting one specific row, modify the required data, and save it. Modified data immediately display on the screen in the proper or expected view.

Key Fields: Grid view provided multiple key fields for presenting or handling big data from the data source.

Hyperlink: Grid view give good utility of handling multiple data source specifically on the hyperlink columns. Hyperlink columns have verities fields which developer can utilize as per their requirement.

Themes & Style: Grid view provides the ability of multiple appearances which can be easily handled by themes & style utilities have given by Grid view.

Example to Implement chúng tôi Grid View

Creating a grid view presentation in chúng tôi application, developer normally needs to use below specific code:

Entire GridView presentation can be done by one behind the ASPX code for handling the dashboard and proper presentation.

Binding data in the GridView dashboard presentation with specific columns.

Edit corresponding data in the grid view.

Delete specific rows from the dashboard.

HTML code:

<asp:GridView runat=”server” AutoGenerateColumns=”False” OnRowEditing=”GridView1_RowEditing” OnRowUpdating=”GridView1_RowUpdating” OnRowCancelingEdit=”GridView1_RowCancelingEdit” <asp:RequiredFieldValidator runat=”server” ControlToValidate=”TextBox2″ <asp:RequiredFieldValidator runat=”server” ControlToValidate=”TextBox4″

Adding Page:

Binding:

public void BindMyGridview() { if (Session["myDatatable"] != null) { DataTable dt = (DataTable)Session["myDatatable"]; { GridView1.Visible = true; GridView1.DataSource = dt; GridView1.DataBind(); } else { GridView1.Visible = false; } } }

Row Updating:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { TextBox TextBoxWithID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2"); TextBox TextBoxWithName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4"); string NewID = TextBoxWithID.Text.ToString(); string NewName = TextBoxWithName.Text.ToString(); DataTable dt = (DataTable)Session["myDatatable"]; DataRow dr = dt.Rows[e.RowIndex] dr["ID"] = NewID; dr["Name"] = NewName; dr.AcceptChanges(); Session["myDatatable"] = dt; GridView1.EditIndex = -1; BindMyGridview(); }

Row Deleting:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { DataTable dt = (DataTable)Session["myDatatable"]; DataRow dr = dt.Rows[e.RowIndex]; dt.Rows.Remove(dr); GridView1.EditIndex = -1; BindMyGridview(); }

Select DOT NET Framework 3.5 from the drop-down.

Open the page design page, where all the attribute needs to be designed.

Take one new form for proper design. Inside the form, the table has been designed. ID and Name are there where specific data table data should display.

Choose a specific online template for writing the background logic of the Grid View presentation.

Preparing the code for the application and mapping the corresponding field for further execution.

Choosing specific data sources for using and presenting Grid view data as per requirement.

Designing the dashboard also been executing in the preview page, displaying require information.

Writing the ASPX code for preparing the view presentation. It automatically came based on the page design.

Working with a text box to define the field name, catch with the value, and perform the required tasks.

Set one specific dashboard page as a starting page for running the application.

Add multiple data for generating a proper grid view presentation.

Add another data for the proper grid view dashboard presentation.

Adding one more data for displaying more in the dashboard.

Displaying the main dashboard of grid view, where all the added data properly displayed on the screen including edit and delete link.

After the update, this page again returns back to the dashboard with a proper grid view.

The delete button is there for deleting one specific record from the grid view presentation.

Conclusion

ASP.net Grid view presentation is one of the common and key requirements from any of the clients in the current scenario. This presentation or designing the page is comparatively easy to do for the developer rather than performing normal design. The page has multiple fields to handle and present. Every field is actually bound with corresponding data coming from the backend code.

Recommended Articles

We hope that this EDUCBA information on “ASP.NET GridView” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Data Types In R With Example

In this tutorial, you will learn:

What are the Data Types in R?

Following are the Data Types or Data Structures in R Programming:

Scalars

Vectors (numerical, character, logical)

Matrices

Data frames

Lists

Basics types

4.5 is a decimal value called numerics.

4 is a natural value called integers. Integers are also numerics.

TRUE or FALSE is a Boolean value called logical binary operators in R.

The value inside ” ” or ‘ ‘ are text (string). They are called characters.

We can check the type of a variable with the class function

Example 1: # Declare variables of different types # Numeric x <- 28 class(x)

Output:

## [1] "numeric" Example 2: # String y <- "R is Fantastic" class(y)

Output:

## [1] "character" Example 3: # Boolean z <- TRUE class(z)

Output:

## [1] "logical" Variables

Variables are one of the basic data types in R that store values and are an important component in R programming, especially for a data scientist. A variable in R data types can store a number, an object, a statistical result, vector, dataset, a model prediction basically anything R outputs. We can use that variable later simply by calling the name of the variable.

To declare variable data structures in R, we need to assign a variable name. The name should not have space. We can use _ to connect to words.

To add a value to the variable in data types in R programming, use <- or =.

Here is the syntax:

# First way to declare a variable: use the `<-` name_of_variable <- value # Second way to declare a variable: use the `=` name_of_variable = value

In the command line, we can write the following codes to see what happens:

Example 1: # Print variable x x <- 42 x

Output:

## [1] 42 Example 2: y <- 10 y

Output:

## [1] 10 Example 3: # We call x and y and apply a subtraction x-y

Output:

## [1] 32 Vectors

A vector is a one-dimensional array. We can create a vector with all the basic R data types we learnt before. The simplest way to build vector data structures in R, is to use the c command.

Example 1: # Numerical vec_num <- c(1, 10, 49) vec_num

Output:

## [1] 1 10 49 Example 2: # Character vec_chr <- c("a", "b", "c") vec_chr

Output:

## [1] "a" "b" "c" Example 3: # Boolean vec_bool <- c(TRUE, FALSE, TRUE) vec_bool

Output:

##[1] TRUE FALSE TRUE

We can do arithmetic calculations on vector binary operators in R.

Example 4: # Create the vectors vect_1 <- c(1, 3, 5) vect_2 <- c(2, 4, 6) # Take the sum of A_vector and B_vector sum_vect <- vect_1 + vect_2 # Print out total_vector sum_vect

Output:

[1] 3 7 11 Example 5:

In R, it is possible to slice a vector. In some occasion, we are interested in only the first five rows of a vector. We can use the [1:5] command to extract the value 1 to 5.

# Slice the first five rows of the vector slice_vector <- c(1,2,3,4,5,6,7,8,9,10) slice_vector[1:5]

Output:

## [1] 1 2 3 4 5 Example 6:

The shortest way to create a range of values is to use the: between two numbers. For instance, from the above example, we can write c(1:10) to create a vector of value from one to ten.

# Faster way to create adjacent values c(1:10)

Output:

## [1] 1 2 3 4 5 6 7 8 9 10 R Arithmetic Operators

We will first see the basic arithmetic operators in R data types. Following are the arithmetic and boolean operators in R programming which stand for:

Operator Description

+ Addition

– Subtraction

* Multiplication

/ Division

^ or ** Exponentiation

Example 1: # An addition 3 + 4

Output:

## [1] 7

You can easily copy and paste the above R code into Rstudio Console. The output is displayed after the character #. For instance, we write the code print(‘Guru99’) the output will be ##[1] Guru99.

The ## means we print output and the number in the square bracket ([1]) is the number of the display

Example 2: # A multiplication 3*5

Output:

## [1] 15 Example 3: # A division (5+5)/2

Output:

## [1] 5 Example 4: # Exponentiation 2^5

Output:

Example 5: ## [1] 32 # Modulo 28%%6

Output:

## [1] 4 R Logical Operators

With logical operators, we want to return values inside the vector based on logical conditions. Following is a detailed list of logical operators of data types in R programming

Logical Operators in R

The logical statements in R are wrapped inside the []. We can add as many conditional statements as we like but we need to include them in a parenthesis. We can follow this structure to create a conditional statement:

variable_name[(conditional_statement)] Example 1: # Create a vector from 1 to 10 logical_vector <- c(1:10)

Output:

## [1]FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE Example 2:

In the example below, we want to extract the values that only meet the condition ‘is strictly superior to five’. For that, we can wrap the condition inside a square bracket precede by the vector containing the values.

# Print value strictly above 5

Output:

## [1] 6 7 8 9 10 Example 3: # Print 5 and 6 logical_vector <- c(1:10)

Output:

## [1] 5 6

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’.

Examples

Here 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 #2

In 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 #3

This 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 #4

In 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:

Conclusion

In 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 Articles

This 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

Syntax

Before 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 #1

0: 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 umask

Output:

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 permission

The 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 Permission

The 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 umask

Code:

mkdir new DirWO touch new FileWO ls -l

Output:

With umask

Code:

umask 027 mkdir newDir touch new File ls -l

Output:

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.

Conclusion

In 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 Articles

We hope that this EDUCBA information on “Linux Umask” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Mutex Work In Go Language With Examples?

Introduction to Golang Mutex

Web development, programming languages, Software testing & others

Syntax of Golang Mutex

In 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 Mutex

Given below are the examples mentioned:

Example #1

In 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 #2

Code:

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:

Conclusion

From 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 Articles

This 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 –

Update the detailed information about How To Work With File In Lua With Example? 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!